useEffect 如何处理 async
# 背景
Argument of type '() => Promise<void>' is not assignable to parameter of type 'EffectCallback'.
1
# 不需要返回值的情况
const MyFunctionnalComponent: React.FC = props => {
useEffect(() => {
// Create an scoped async function in the hook
async function anyNameFunction() {
await loadContent();
}
// Execute the created function directly
anyNameFunction();
}, []);
return <div></div>;
};
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
or iife
const MyFunctionnalComponent: React.FC = props => {
useEffect(() => {
// Using an IIFE
(async function anyNameFunction() {
await loadContent();
})();
}, []);
return <div></div>;
};
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 如果有返回值的情况
const MyFunctionnalComponent: React.FC = props => {
const tmp = useRef(null)
useEffect(() => {
// Using an IIFE
(async function anyNameFunction() {
tmp.current = await loadContent();
})();
return {
if(tmp.current){
console.log(tmp.current)
}
}
}, []);
return <div></div>;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 使用 useAsyncEffect hooks
useAsyncEffect - ahooks (opens new window)
# 参考文献
编辑 (opens new window)
上次更新: 2023/08/23, 09:32:05