【发布时间】:2022-11-05 04:21:59
【问题描述】:
我尝试了下面的代码来私有路由管理仪表板 我正在使用 react-router-dom:6.2.2。我需要帮助来确定只能由管理员访问的私有路由。我尝试了 stackoverflow 中的所有现有解决方案。
应用程序.js
<BrowserRouter>
<Routes>
<Route path="/admin/dashboard" element={<PrivateRouter><Dashboard /> </PrivateRouter>} />
</Routes>
</BrowserRouter>
私有路由器.js
<Route
{...rest}
component={(props) => {
const token = window.localStorage.getItem("userInfo");
console.log(token)
if (token) {
return <Component {...props} />;
} else {
return <Navigate to={"/login"} />;
}
}}
/>
);
}
及其在控制台上的抛出错误
index.tsx:24 Uncaught Error: A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.
at invariant (index.tsx:24:1)
at Route (index.tsx:235:1)
at renderWithHooks (react-dom.development)
【问题讨论】:
-
该错误准确地解释了出了什么问题
-
但即使我不能使用 <Private Router path="/admin/dashboard" element={<Dashboard />} /> } 也找不到任何其他解决方案
-
在提问时,解释你需要什么,你尝试了什么,你得到了什么。您做了其中两个,但也请添加您需要的内容,这可能有助于您的问题快速得到答案
标签: reactjs