首页 > 解决方案 > 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。我怎样才能正确使用它?谢谢你

标签: javascriptreactjstypescriptreact-router

解决方案


您不应该在条件内使用钩子,这违反了钩子规则,因此您可能最终在组件内部出现过时状态,请阅读此https://reactjs.org/docs/hooks-rules.html

你的代码应该像

useEffect(() => { 
 if (redirectUrl) {
   window.location.replace(redirectUrl!);

 } else {
   <Redirect to={'/page'} />;
 }
});

对于 redirectUrl 也使用完整的 url,包括协议


推荐阅读