【问题标题】:React.js, inside useEffect hook, window.location.href will not stop break further code from executionReact.js,在 useEffect 挂钩中,window.location.href 不会停止中断进一步的代码执行
【发布时间】:2021-08-27 09:08:06
【问题描述】:

最近发现,如果我使用window.location.href进行重定向,而我没有指定return {},那么后面的代码会继续执行,这不是我想要的。

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

  1. React.js useEffect 钩子。
  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();
  }, []);

【问题讨论】:

    标签: javascript reactjs async-await react-hooks window.location


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2017-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多