清理 useEffect React 钩子中的异步函数

Cha*_*wis 4 async-await reactjs react-hooks

我有以下 useEffect 函数,并试图找到在组件卸载时清理它的最佳方法。

我认为最好遵循makeCancelableReact文档中的,但是,当 Promise 被取消时,代码仍然会执行。

const makeCancelable = (promise) => {
  let hasCanceled_ = false;

  const wrappedPromise = new Promise((resolve, reject) => {
    promise.then(
      val => hasCanceled_ ? reject({isCanceled: true}) : resolve(val),
      error => hasCanceled_ ? reject({isCanceled: true}) : reject(error)
    );
  });

  return {
    promise: wrappedPromise,
    cancel() {
      hasCanceled_ = true;
    },
  };
};
Run Code Online (Sandbox Code Playgroud)
//example useEffect
useEffect(() => {
  const getData = async () => {
    const collectionRef_1 = await firestore.collection(...)
    const collectionRef_2 = await firestore.collection(...)
    if (collectionRef_1.exists) {
      //update local state
      //this still runs!
    }
    if (collectionRef_2.exists) {
      //update local state
      //and do does this!
    }
  }
  const getDataPromise = makeCancelable(new Promise(getData))
  getDataPromise.promise.then(() => setDataLoaded(true))
  return () => getDataPromise.cancel()
}, [dataLoaded, firestore])
Run Code Online (Sandbox Code Playgroud)

我也试过const getDataPromise = makeCancelable(getData)没有任何运气。代码执行得很好,只是在组件卸载时没有正确清理。

我还需要取消两个等待功能吗?

Ras*_*mon 5

在您的makeCancelable函数中,您只是hasCanceled_ 在承诺完成后检查的值(意思getData是已经完全执行):

const makeCancelable = (promise) => {
  let hasCanceled_ = false;

  const wrappedPromise = new Promise((resolve, reject) => {
    // AFTER PROMISE RESOLVES (see following '.then()'!), check if the 
    // react element has unmount (meaning the cancel function was called). 
    // If so, just reject it
    promise.then(
      val => hasCanceled_ ? reject({isCanceled: true}) : resolve(val),
      error => hasCanceled_ ? reject({isCanceled: true}) : reject(error)
    );
  });

  return {
    promise: wrappedPromise,
    cancel() {
      hasCanceled_ = true;
    },
  };
};
Run Code Online (Sandbox Code Playgroud)

相反,在这种情况下,我建议您采用更简单、更经典的解决方案,并使用isMounted变量来创建您想要的逻辑:

useEffect(() => {
  let isMounted = true
  const getData = async () => {
    const collectionRef_1 = await firestore.collection(...)
    const collectionRef_2 = await firestore.collection(...)
    if (collectionRef_1.exists && isMounted) {
      // this should not run if not mounted
    }
    if (collectionRef_2.exists && isMounted) {
      // this should not run if not mounted
    }
  }
  getData().then(() => setDataLoaded(true))
  return () => {
    isMounted = false
  }
}, [dataLoaded, firestore])
Run Code Online (Sandbox Code Playgroud)