Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React 异步操作回收 #62

Open
jtwang7 opened this issue Apr 27, 2023 · 0 comments
Open

React 异步操作回收 #62

jtwang7 opened this issue Apr 27, 2023 · 0 comments

Comments

@jtwang7
Copy link
Owner

jtwang7 commented Apr 27, 2023

React 异步操作回收

计时器回收

计时器我们可以用对应的注销方法来回收计时器的异步回调

useEffect(() => {
  const id = requestAnimationFrame(startAnimate1);
  const timerId = setTimeout(startAnimate2);
  const intervalId = setInterval(startAnimate3);
  return () => {
    cancelAnimationFrame(id);
    clearTimeout(timerId);
    clearInterval(intervalId);
  }
}, []);

插桩回收

针对 Promise 这类没有原生回收方案的的异步操作,比较通用的方法是插桩回收

useEffect(() => {
  let canceled = false
  fetchData(pageIindex).then(resp => {
    if (canceled) {
      return;
    }
    // DO SOMETHING UI UPDATE
  });
  return () => canceled = true;
}, [pageIndex]);

上面的代码,定义了一个标志位(canceled),通过函数闭包在异步回调的时候,判断是否标志位已经过期(canceled = true),如果过期,不执行回调。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant