如何在react路由器dom中动态重定向



我使用的是一个自定义挂钩,如果用户登录,它将返回true,否则将返回false。

useAuth.js

从"导入{useEffect,useState};反应";;

const useAuth = () => {
const [isAuth, setIsAuth] = useState();
useEffect(() => {
setIsAuth(localStorage.getItem("auth"));
}, []);
if (!!isAuth) {
console.log("Auth", isAuth);
return true;
}
return false;
};
export default useAuth;

如果登录,我想动态地将用户重定向到/dashboard,如果未登录,则重定向到/login。

登录.jsx

const Login = () => {
function onLogin() {
localStorage.setItem("auth", "token");
}
return <button onClick={onLogin}>Login</button>;
};
export default Login;

Dashboard.jsx

const Dashboard = () => {
return <h1>Dashboard</h1>;
};
export default Dashboard;

我有一个单独的文件用于处理路由

Router.js

import { BrowserRouter, Redirect, Route, Switch } from "react-router-dom";
import useAuth from "./useAuth";
import Dashboard from "./Dashboard";
import Login from "./Login";
const Router = () => {
const isAuth = useAuth();
const routes = [
{
path: "/login",
component: Login,
},
{
path: "/dashboard",
component: Dashboard,
},
];
return (
<>
<BrowserRouter>
<Switch>
{routes.map((route) => {
return (
<Route
key={route.path}
exact
path={route.path}
component={route.component}
/>
);
})}
<Redirect to={isAuth ? "/dashboard" : "/login"} />
</Switch>
</BrowserRouter>
</>
);
};
export default Router;

但它总是被重定向到"/登录";。有什么办法解决这个问题吗?

Codesandbox链接:https://codesandbox.io/s/inspiring-joliot-h89gq?file=/src/Router.js

@Abi-Place重定向语句在switch语句之外,它将起作用。有关更多信息,请参阅github-https://github.com/ReactTraining/react-router/issues/6840.

最新更新