我正在尝试用新发布的路由器实现一个PrivateRoute逻辑,但它似乎没有像预期的那样工作。
import { Route, Routes, Navigate } from "react-router-dom";
import LogInPage from "./pages/LogIn";
import DashboardPage from "./pages/Dashboard";
function PrivateRoute({ path, element }) {
const auth = true;
return (
<Route
path={path}
element={auth === true ? element : <Navigate replace to="/login" />}
/>
);
}
function App() {
return (
<Routes>
<Route path="/*" element={<PageNotFound />} />
<Route path="/" element={<Navigate replace to="/dashboard" />} />
<Route path="/login" element={<LogInPage />} />
<PrivateRoute
path="/dashboard"
element={<DashboardPage />}
/>
</Routes>
);
}
export default App;我遗漏了什么?如果PrivateRoute组件返回一个Route,那么它不是仍然是一个Route组件吗?
发布于 2021-11-10 13:57:02
React路由器v6中的You cannot compose Route%s。相反,应在与其他路由相同的级别创建路由,并在element属性中使用PrivateRoute组件。示例(source):
import { Routes, Route, Navigate } from "react-router-dom";
function App() {
return (
<Routes>
<Route path="/public" element={<PublicPage />} />
<Route
path="/protected"
element={
// Good! Do your composition here instead of wrapping <Route>.
// This is really just inverting the wrapping, but it's a lot
// more clear which components expect which props.
<RequireAuth redirectTo="/login">
<ProtectedPage />
</RequireAuth>
}
/>
</Routes>
);
}
function RequireAuth({ children, redirectTo }) {
let isAuthenticated = getAuth();
return isAuthenticated ? children : <Navigate to={redirectTo} />;
}https://stackoverflow.com/questions/69868011
复制相似问题