問題
以下程式碼嘗試建立使用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中文網其他相關文章!