javascript - 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>
);
}
您可以根据您的用例和方法使用任何您需要的东西。
推荐阅读
- scala - 从列表中获取并排序最大的元组
- c# - 为什么带有类型信息的 JSON 序列化对象会出错?
- c# - 获取 LINQ 笛卡尔积的单个项目
- ruby-on-rails - Rake 命令在终端中有效,但在 crontab 中无效
- android - 创建设置活动时的布尔参数问题
- android - 移动版中的空白(角度 6 mat-dialog)
- mysql - SQL:选择重复值的第一个出现的行
- c# - 在 Visual Studio 中检索建议的代码替代方案(可能是 Resharper)
- javascript - 自动完成时突出显示/粗体文本
- aws-lambda - AWS Lambda 函数正在使用 SAM Local 工具,但不在云上