[英]React Router Redirect not firing after history.push used
[英]React Router Docs & Redirect vs history.push()
我试图阅读以前的答案,但不幸的是他们只提出了更多问题。 在注销后第 124 行的反应路由器文档https://reactrouter.com/web/example/auth-workflow中,他们使用 history.push("/")
history.push() 这里的目的是什么,为什么不使用 Redirect 呢?
Redirect
更多的是在某些逻辑存在或不存在的情况下呈现的组件,请考虑以下示例,它通常用于当您在路由上有一些逻辑并想要进行条件重定向时。
类似地,当您有一些事件触发操作时,您使用history.push
,例如您单击一个按钮,这反过来会进行一些验证,然后可能会根据您的业务逻辑重定向您。
我已经给出了这两种情况的例子,希望它有所帮助。
const Admin = () => {
const [isInvalidUser, setUserInvalid] = useState(false);
useEffect(() => {
// check if valid user via API call
setUserInvalid(true);
}, [])
// here you are returning a component in form of Redirect
// this is automatically executed when you open a particular route, it is not event triggered
if(isInvalidUser) {
return <Redirect to="/auth" />;
}
return <AdminView />;
}
const Login = () => {
const handleLogin = () => {
// business logic to validate login
if(validUser) {
// you cannot have return statement here with Redirect as this is a handler
history.push("/home");
}
}
// assume you have state for username and password
return (
<button onClick={handleLogin}>Submit</button>
);
}
您可以根据您的用例和方法使用任何您需要的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.