【问题标题】:React customHook using useEffect with async使用 useEffect 和 async 反应 customHook
【发布时间】:2020-11-25 01:18:51
【问题描述】:

我有一个使用 useEffect 的 customHook,我希望它在 useEffect 完成后返回结果,但是,它总是在我的异步方法完成之前返回......

// customHook
const useLoadData = (startLoading, userId, hasError) => {
  const [loadDone, setLoadDone] = useState(false);
  const loadWebsite = async(userId) => {
     await apiService.call(...);
     console.log('service call is completed');
     dispatch(someAction);
  }

  useEffect(() => {
    // define async function inside useEffect
    const loadData = async () => {
       if (!hasError) {
          await loadWebsite();
       }
    }

    // call the above function based on flag
    if (startLoading) {
       await loadData();
       setLoadDone(true);
    } else {
      setLoadDone(false);
    }
  }, [startLoading]);

  return loadDone;
}

// main component
const mainComp = () => {
   const [startLoad, setStartLoad] = useState(true);
   const loadDone = useLoadData(startLoad, 1, false);
   useEffect(() => {
       console.log('in useEffect loadDone is: ', loadDone);
       if (loadDone) {
          // do something
          setStartLoad(false); //avoid load twice
       } else {
          // do something
       }
   }, [startLoad, loadDone]);
   useAnotherHook(loadDone); // this hook will use the result of my `useLoadData` hook as an execution flag and do something else, however, the `loadDone` always false as returning from my `useLoadData` hook
}

似乎在我的 useDataLoad 钩子中,它不会等到我的异步函数 loadData 完成,而是始终将 loadDone 返回为 false,即使我已将 await 关键字放入我的 loadData 函数,并且setLoadDone(true) 之后,它仍然总是返回 false,我在这里的实现会有什么问题,我如何通过 customHook 中的异步方法返回正确的值?

【问题讨论】:

  • 你传递给useEffect的函数不是async,所以我很惊讶你不会得到某种编译器错误,表明它需要async才能能够使用await
  • @EvanTrimboli 嗨,我在useEffect 中定义的函数是loadData,它将调用异步函数loadWebsite,为什么它不认为没有异步?
  • 不是loadData,您传递给useEffect 的第一个参数。这不是“异步”。

标签: javascript reactjs async-await react-hooks use-effect


【解决方案1】:

嗯...在我将setLoadDone(true); 放入我的异步方法而不是useEffect 之后,它似乎工作了,虽然我不知道为什么... 更新代码:

// customHook
const useLoadData = (startLoading, userId, hasError) => {
  const [loadDone, setLoadDone] = useState(false);
  const loadWebsite = async(userId) => {
     await apiService.call(...);
     console.log('service call is completed');
     dispatch(someAction);
     setLoadDone(true);
  }

  useEffect(() => {
    // define async function inside useEffect
    const loadData = async () => {
       if (!hasError) {
          await loadWebsite();
       }
    }

    // call the above function based on flag
    if (startLoading) {
       await loadData();
       // setLoadDone(true); doesn't work here
    }
  }, [startLoading]);

  return loadDone;
}

【讨论】:

  • 您仍然有语法错误:Uncaught SyntaxError: await is only valid in async function。这里对await loadData的调用不正确,你不能await它。
猜你喜欢
  • 1970-01-01
  • 2020-05-07
  • 2021-08-28
  • 2021-07-31
  • 2021-05-11
  • 1970-01-01
  • 2021-03-12
  • 2021-10-03
  • 2021-10-03
相关资源
最近更新 更多