[英]React Router rendering blank pages for all components
我目前正在学习关于 react-router-dom 的教程,每当我将我的三个路由放入Router
时,在拉起 localhost 时,我总是在所有三个路由上得到空白页面。 我正在使用path
和element
在element
属性内使用三元运算符配置路由,但在渲染时我仍然得到一个空白页面。 知道为什么会这样吗? 谢谢!
应用程序.js
import React, { Fragment, useState, useEffect } from "react";
import {
BrowserRouter as Router,
Route,
Switch,
Redirect
} from "react-router-dom";
//components
import Login from "./components/Login";
import Register from "./components/Register";
import Dashboard from "./components/Dashboard";
function App() {
const checkAuthenticated = async () => {
try {
const res = await fetch("http://localhost:5000/auth/verify", {
method: "GET",
headers: { token: localStorage.token }
});
const parseRes = await res.json();
parseRes === true ? setIsAuthenticated(true) : setIsAuthenticated(false);
} catch (err) {
console.error(err.message);
}
};
useEffect(() => {
checkAuthenticated();
}, []);
const [isAuthenticated, setIsAuthenticated] = useState(false);
const setAuth = boolean => {
setIsAuthenticated(boolean);
};
return (
<Fragment>
<Router>
<div className="container">
<Switch>
<Route
path="/login"
element={
!isAuthenticated ? (
<Login setAuth={setAuth} />
) : (
<Redirect to="/dashboard" />
)
}
/>
<Route
path="/register"
element={
!isAuthenticated ? (
<Register setAuth={setAuth} />
) : (
<Redirect to="/dashboard" />
)
}
/>
<Route
path="/dashboard"
element={
isAuthenticated ? (
<Dashboard setAuth={setAuth} />
) : (
<Redirect to="/login" />
)
}
/>
</Switch>
</div>
</Router>
</Fragment>
);
}
export default App;
react-router-dom@5
中的Route
组件没有element
属性, element
是一个 v6 属性。
请改用 `render function 属性。
例子:
<Switch>
<Route
path="/login"
render={props => !isAuthenticated
? (
<Login setAuth={setAuth} {...props} />
) : (
<Redirect to="/dashboard" />
)
}
/>
<Route
path="/register"
render={props => !isAuthenticated
? (
<Register setAuth={setAuth} {...props} />
) : (
<Redirect to="/dashboard" />
)
}
/>
<Route
path="/dashboard"
render={props => isAuthenticated
? (
<Dashboard setAuth={setAuth} {...props} />
) : (
<Redirect to="/login" />
)
}
/>
</Switch>
在确认身份验证之前,未经身份验证的 state 可能与您的初始 state 匹配。 使用初始的isAuthenticated
state 值,该值既未经过身份验证也未经过身份验证,即既不是真也不是假。 使用此“第三个”state 值有条件地呈现 null 或一些其他加载指示器,同时解决身份验证状态。
例子:
const [isAuthenticated, setIsAuthenticated] = useState();
if (isAuthenticated === undefined) {
return null; // or loading spinner, etc...
}
return (
... routes & UI ...
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.