来自异步钩子的同步值

问题描述 投票:0回答:1

我在反应中有这个自定义钩子。

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
仍然是异步的。 那么我怎样才能返回获取的文件呢?

我已经搜索过了,也有类似的问题,但我找不到任何解决方案。

reactjs typescript hook
1个回答
0
投票

我认为你应该将

useEffect
里面的函数设置为异步的,像这样:

useEffect(() => {
  const handleFetch = async() =>{
    let res = await fetch(url.href);
    // Your other code
  }
  handleFetch()
}), []);
© www.soinside.com 2019 - 2024. All rights reserved.