javascript - React 没有正确重定向
问题描述
我正在尝试检查一个条件并基于该条件将页面重定向到不同的路径。我正在使用以下逻辑:
if (redirectUrl) {
useEffect(() => {
window.location.replace(redirectUrl!);
});
} else {
return <Redirect to={'/page'} />;
}
但这个逻辑不能正常工作。如果我的 url 是www.myUrl.com
并且重定向是www.redirectUrl.com
,则此逻辑将我重定向到www.myUrl.com/www.redirectUrl.com
...它不会删除第一个 url。我怎样才能正确使用它?谢谢你
解决方案
您不应该在条件内使用钩子,这违反了钩子规则,因此您可能最终在组件内部出现过时状态,请阅读此https://reactjs.org/docs/hooks-rules.html
你的代码应该像
useEffect(() => {
if (redirectUrl) {
window.location.replace(redirectUrl!);
} else {
<Redirect to={'/page'} />;
}
});
对于 redirectUrl 也使用完整的 url,包括协议
推荐阅读
- nginx - Nginx 轮询负载均衡不如预期
- excel - 是否可以基于锁定的模板添加新工作簿
- javascript - 在酶中为服务调用编写测试 - 反应
- visual-studio - Subversion - 无法提交消息和查看历史记录
- mysql - 将第二高的日期与最新的日期进行比较
- sql - 查询count和distinct
- javascript - React:提交表单时子组件不渲染
- html - 使我的网站部分透明以在浏览器后面显示桌面
- c - 为什么当我在 fork() 之前使用 dup2() 时它不起作用?
- python - TensorFlow Memory 总是超过 10% 的系统内存