问题
以下代码尝试创建使用react-router-dom的React应用程序中的受保护路由:
import { useContext } from "react"; import { globalC } from "./context"; import { Route, Switch, BrowserRouter } from "react-router-dom"; import About from "./About"; import Dashboard from "./Dashboard"; import Login from "./Login"; import PageNotFound from "./PageNotFound"; function Routes() { const { authLogin } = useContext(globalC); console.log("authLogin", authLogin); return ( <BrowserRouter> <Switch> {authLogin ? ( <> <Route path="/dashboard" component={Dashboard} exact /> <Route exact path="/About" component={About} /> </> ) : ( <Route path="/" component={Login} exact /> )} <Route component={PageNotFound} /> </Switch> </BrowserRouter> ); } export default Routes;
但是,此代码无法按预期工作。即使用户未登录,也可以访问受保护的路由。
解决方案
主要有两个问题代码如下:
这里是修正了这两个问题的代码版本:
import { useContext } from "react"; import { globalC } from "./context"; import { Route, Switch, BrowserRouter, Redirect } from "react-router-dom"; import About from "./About"; import Dashboard from "./Dashboard"; import Login from "./Login"; import PageNotFound from "./PageNotFound"; function Routes() { const { authLogin } = useContext(globalC); console.log("authLogin", authLogin); return ( <BrowserRouter> <Switch> <Route path="/" exact> {authLogin ? <Redirect to="/dashboard" /> : <Login />} </Route> <Route path="/dashboard"> {authLogin ? <Dashboard /> : <Redirect to="/" />} </Route> <Route exact path="/About" component={About} /> <Route component={PageNotFound} /> </Switch> </BrowserRouter> ); } export default Routes;
在此更正的代码:
以上是如何在React Router Dom中正确实现受保护的路由?的详细内容。更多信息请关注PHP中文网其他相关文章!