[英]How Could I redirect login page using Javascript
const RequireAuth = ({ children }) => {
const [user, loading, error] = useAuthState(auth);
const location = useLocation();
if (loading) {
return <Loading></Loading>
}
if (!user) {
return <Navigate to="/login" state={{ from: location }} replace />;
}
return children;
};
export default RequireAuth;
You can also do something like this:你也可以这样做:
if (!user) {
window.location.href = `http://localhost:3000/login?from=${location}` // for example
}
and then parse query string to get a value of location
然后解析查询字符串以获取location
值
UPDATE:更新:
Doing "routing" as I mentioned above is wrong and it will lead to hard to debug bugs.像我上面提到的那样做“路由”是错误的,它会导致难以调试错误。 Use useNavigate
hook from react-router-dom
instead: https://reactrouter.com/docs/en/v6/hooks/use-navigate使用来自react-router-dom
useNavigate
挂钩: https://reactrouter.com/docs/en/v6/hooks/use-navigate
const [user, loading] = use Auth State(auth)
const location = use Location()
if (loading) {
return <Loading></Loading>
}
if (!user) {
return <Navigate to="/login" state={{ from: location }} replace ></Navigate>
}
return children
}; };
export default Private Route;导出默认私有路由;
(sorry for space) (对不起空间)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.