使用react-router-dom的useNavigate导致页面渲染后报错
问题根源及修复点:
App.js里的Login路由语法错误
你写的<Route path="/login"/> element={<Login />}/>多了个闭合的/>,导致路由配置失效,直接引发渲染异常。useEffect回调不能直接用async
useEffect的回调函数不能是async函数——因为async会返回Promise,而React要求useEffect的回调要么返回清理函数,要么返回undefined。这种写法会触发React内部错误,最终导致页面空白。Home组件未导入
App.js里用了<Home />但没导入这个组件,会直接报错导致渲染失败。useEffect依赖数组缺项
虽然navigate是稳定引用,但按照React Hooks规则,得把它加到依赖数组里,避免潜在的闭包问题。
修正后的代码:
App.js
import Appbar from './appbar.jsx'; import { Route, Routes } from 'react-router-dom'; import Login from "./components/login/login.jsx"; import ProfilePage from "./components/profilePage/profilePage.jsx"; // 记得导入Home组件,路径根据你的实际项目调整 import Home from "./components/home/home.jsx"; export default function App() { return ( <div className="App"> <Appbar/> <> <Routes> <Route path="/" element={<Home /> }/> {/* 修正Login路由的语法错误 */} <Route path="/login" element={<Login />}/> <Route path="/profilePage" element={<ProfilePage />}/> </Routes> </> </div> ); }
Login.jsx
import { useNavigate } from 'react-router-dom'; import { useEffect } from 'react'; export default function Login(props) { const navigate = useNavigate(); // 把async逻辑封装到内部函数里,不要直接给useEffect传async回调 useEffect(() => { const checkUserAuth = async () => { const response = await fetch('/users/userAuth', { method: 'POST', headers: { 'x-access-token': localStorage.getItem('token'), }, }); const data = await response.json(); if (data.isLoggedIn === true) { navigate("/profilePage"); } else { console.log("not logged in"); } }; checkUserAuth(); }, [navigate]) // 添加navigate到依赖数组 // 给Login组件加个默认渲染内容,避免验证过程中页面一片空白 return ( <div> <h1>登录页</h1> {/* 这里可以放你的登录表单 */} </div> ); }
这些修改做完后,应该就能解决跳转后页面空白的问题了:路由配置正常,useEffect符合规则,组件依赖也完整,不会再触发React的错误导致页面崩溃。
内容的提问来源于stack exchange,提问作者LaElijah
相关产品推荐
相关产品推荐

