简体   繁体   English

影响相同的两个 React useEffect 函数 state

[英]Two React useEffect functions affecting the same state

I have a certain piece of state that is updated via api calls.我有一段 state 是通过 api 调用更新的。 I have multiple components that affect this state and am running into an issue.我有多个影响此 state 的组件并且遇到了问题。 Basically, the issue comes down to how the state is set because of the time it takes for the api call to finish.基本上,问题归结为 state 的设置方式,因为 api 调用完成需要时间。

Basically: Component 1 is loaded and the useEffect is triggered to update the state Component 2 is loaded right afterwards and also has a useEffect making the same api call for different data基本上:加载组件 1 并触发 useEffect 以更新 state 组件 2 随后立即加载,并且还有一个 useEffect 对不同的数据进行相同的 api 调用

If the api call in Component 1 takes longer than Component 2, Component 2's set state is then overwritten by the set state of Component 1 once its api call finishes, even if Component 1 is no longer mounted.如果组件 1 中的 api 调用花费的时间比组件 2 长,则一旦组件 1 的 api 调用完成,组件 2 的集合 state 就会被组件 1 的集合 state 覆盖,即使组件 1 不再安装。

Is there a way in functional components to cancel any api calls/setting of state when the component is unmounted?功能组件中是否有一种方法可以在卸载组件时取消 state 的任何 api 调用/设置? Thanks.谢谢。

I found the basic answer here in this other question: Canceling an Axios REST call in React Hooks useEffects cleanup failing我在这里找到了另一个问题的基本答案: Cancelling an Axios REST call in React Hooks useEffects cleanup failing

Basically, I needed to have the useEffect function return something in order for it to be cleaned up.基本上,我需要让 useEffect function 返回一些东西以便清理它。 It is easier to explain in code, so I will put that below:用代码更容易解释,所以我将其放在下面:

  useEffect(() => {
    let unMounted = false;
    const onLoad = async () => {
      const data= await axios.get();
      !unMounted &&
        setData(data);
    };

    onLoad();

    return () => {
      unMounted = true;
    };
  }, []);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM