我在反应中有这个自定义钩子。
export default function useAPI(path: string) {
let [file, setFile] = useState<any>(null);
let url = new URL(path);
useEffect(() => {
let res = await fetch(url.href);
// some other code
}), []);
return file;
}
当我从其他组件使用它时
import useAPI from '...';
export default function App() {
let file = useAPI('pathtofile.json');
}
返回值为
null
。发生这种情况是因为 return file
是同步的,而 file
的默认状态是 null
而 fetch
仍然是异步的。
那么我怎样才能返回获取的文件呢?
我已经搜索过了,也有类似的问题,但我找不到任何解决方案。
我认为你应该将
useEffect
里面的函数设置为异步的,像这样:
useEffect(() => {
const handleFetch = async() =>{
let res = await fetch(url.href);
// Your other code
}
handleFetch()
}), []);