我有一个主组件MainComp,它调用子组件ChildComp,像这样:
<ChildComp data={data}>
这是ChildComp:
export const ChildComp = (props: any) => {
console.log("#1");
const { value, loading, error } = useAsync(async (): Promise<any> => {
console.log("#2");
const response = await fetch(<some url>);
const data = await response.json();
return data;
}, []);
}
if (loading) {
// return
} else if (error) {
// return
}
return value;
当在页面加载时初始调用子组件时,一切正常工作。但是,当子组件的props被更改时,组件会被重新加载,但不会调用useAsync钩子。结果,在控制台上打印的是#1,而不是#2。
任何想法我可以调用useAsync()再次当组件被重新加载,因为道具的变化?fetch中的URL会根据传入的道具而变化,因此每次有变化时都需要调用。
谢谢你的帮助!
您需要为useAsync()
钩子提供正确的依赖项:
const { value, loading, error } = useAsync(async (): Promise<any> => {
// ...
}, []); // <---- Indicate here the props/url upon which change you want to re-fetch data