简体   繁体   English

您建议在 useEffect 挂钩中取消订阅的模式是什么?

[英]What would you suggest as pattern for canceling subscriptions in useEffect hook?

Most of you have probably seen this React warning.你们中的大多数人可能已经看到了这个 React 警告。 Me too, and it is clear to my why React gives warns us about unmounting during a state update.我也是,我很清楚为什么 React 会在 state 更新期间警告我们卸载。 But I'm trying to figure out what is the best React pattern prevent a possible memory leak.但我试图弄清楚什么是最好的 React 模式可以防止可能的 memory 泄漏。

Warning: Can't perform a React state update on an unmounted component. 
This is a no-op, but it indicates a memory leak in your application. 
To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

In my projects I'm using this boolean flag didCancel to let my data fetching logic know about the state of the component.在我的项目中,我使用这个 boolean 标志didCancel让我的数据获取逻辑知道组件的 state。 If the component did unmount, the flag should be set to true which results in preventing to set the component state after the data fetching has been asynchronously resolved eventually.如果组件确实卸载,则该标志应设置为 true,这会导致在最终异步解决数据获取后阻止设置组件 state。

useEffect(() => {
    let didCancel = false;

    const fetchEvents = () => {
      fetch(url, settings)
        .then(res => {
          return res.json();
        })
        .then(({ data }) => {
          if (!didCancel) {
            setEvents(data.events);
          }
        })
        .catch(err => {
          console.log(err);
          if (!didCancel) {
            setLoading(false);
          }
        });
    };

    fetchEvents();

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

So eventhough this works, I just want to know what you guys are using as a pattern.因此,尽管这可行,但我只想知道你们正在使用什么作为模式。 What could be seen as best practice?什么可以被视为最佳实践? Is there remarkable difference when fetching data, then when you're only updating state?获取数据时是否有显着差异,然后仅更新 state? Please let me know!请告诉我!

I prefer using defer from rxjs library for this:我更喜欢为此使用rxjs库中的defer

useEffect(() => {
  const subscription = defer(() =>
    fetch(url, settings).then(response => response.json())
  ).subscribe({
    next: ({ data }) => {
      setEvents(data.events);
    },
    error: () => {
      setLoading(false);
    },
    complete: () => {
      setLoading(false);
    }
  });

  return () => subscription.unsubscribe();
}, []);

What is didCancel supposed to be doing? didCancel应该做什么? It just looks like a local variable you're switching to true on mount.它看起来就像一个局部变量,您在挂载时切换为 true。 Is it used in your fetchEvents ?它是否在您的fetchEvents中使用? Your fetchEvents will never be called after the initial mount初始挂载后永远不会调用您的fetchEvents

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

相关问题 您认为在 Laravel 中翻译数据库记录的最佳解决方案是什么? - What would you suggest as a best solution for translating database records in Laravel? 提前退出 useEffect 钩子是一种反模式吗? - Is it an anti-pattern to exit useEffect hook early? useEffect hook 在 react 中的执行顺序是什么? - What is the order for execution of useEffect hook in react? 您将在ASP.NET中建议哪个JavaScript库? - Which JavaScript library would you suggest in ASP.NET? 使用 React 的 useCallback 钩子代替 useEffect 的意图是什么? - What is the intention of using React's useCallback hook in place of useEffect? useEffect React hook 使用的是什么比较过程? - What comparison process does the useEffect React hook use? 发生了什么将 setInterval 重新定义为 useEffect 挂钩中的变量? - what happend re-define setInterval to variable in useEffect hook? 在 React 的 useEffect 挂钩中使用 Promise 时的操作顺序是什么? - What is the sequence of actions when using promises in useEffect hook in React? reactjs 文档提到了 useEffect 挂钩中的延迟事件,这是什么意思? - reactjs doc mentioned to deferred event in useEffect hook, what it means? 在自定义钩子和组件中使用 useEffect 有什么区别 - what is the difference between using useEffect inside a custom hook and a component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM