【发布时间】: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