首页 > 解决方案 > React.js,在 useEffect 挂钩中,window.location.href 不会停止中断进一步的代码执行

问题描述

最近我发现,如果我使用window.location.href重定向,并且我没有指定return {},进一步的代码将继续执行,这不是我想要的。

如果这与以下内容有关,我可以要求澄清一下:

  1. React.jsuseEffect钩子。
  2. window.location.href默认情况下重定向后不会中断。
  3. 异步等待。
  useEffect(() => {
    const myFunction = () =>
      ajax({
        url: API_ROUTES.MY_EXAMPLE_ROUTE,
        requestBody: {
          request_message: "Hi, pls help!",
        },
        handleSuccess: response => {
          if (condition === true)) {
            window.location.href = "http://google.com";
            // If I do not put return here, code will continue to execute.
            return {}; 
          }
         
          // Code that I do not want to run after redirection
          history.push(routes.error);
          return {};
        },
        handleError: error => {
          history.push(routes.error);
        },
      });
    const init = async () => {
      await myFunction();
    };
    init();
  }, []);

标签: javascriptreactjsasync-awaitreact-hookswindow.location

解决方案


您似乎希望代码在将 设置window.location.href为一个值后停止执行该函数,但这是不正确的。要过早退出函数,您确实需要使用return.

更好的解决方案是使用else条件,以便history.push仅在condition为假时运行。

if (condition) {
  window.location.href = 'http://www.google.com';
} else {
  history.push(routes.error);
}

推荐阅读