【问题标题】:Promise pending when calling a function inside a hook using React使用 React 在钩子内调用函数时的 Promise 挂起
【发布时间】:2022-10-05 06:01:35
【问题描述】:

我正在使用 axios 从 API(对象的 arr)中提取数据,但由于某种原因,在钩子内调用它时,我一直收到未决的承诺。

我使用承诺链来确保代码同步执行,但它仍然是相同的。

例如,当我使用“console.log(selectedVideo[0]”时,我得到“未定义”。我认为这是因为它在完成提取数据之前调用 API,对吗?

    const url = `${baseURL}videos?api_key=${apiKEY}`;

    const fetchData = axios
        .get(url)
        .then((resp) => setSelectedVideo(resp.data));

    useEffect(() => {
        fetchData();
    }, []);

    // sets the state for the video
    const [selectedVideo, setSelectedVideo] = useState(fetchData);

    console.log(selectedVideo);

【问题讨论】:

  • 尝试把 settimeout

标签: javascript reactjs react-hooks axios


【解决方案1】:

此代码将在每个组件重新渲染时执行,即使fetchData 结果不会是function,它将是undefined(从setSelectedVideo 返回),您需要将fetchData 转为函数.

此外,由于数据来自API,您需要为state 设置默认值,例如nullempty object

我认为你正在寻找的是。

    const url = `${baseURL}videos?api_key=${apiKEY}`;

    const fetchData = () => axios
        .get(url)
        .then((resp) => setSelectedVideo(resp.data));

    useEffect(() => {
        fetchData();
    }, []);

    const [selectedVideo, setSelectedVideo] = useState(null);

【讨论】:

  • 啊,那是有道理的。感谢您的详细回答!在这个问题上苦苦挣扎了一段时间哈哈。这让我意识到我也可以在这里减少一点代码......最终做同样的事情。 ``` const [selectedVideo, setSelectedVideo] = useState(null); useEffect(() => { axios.get(url).then((resp) => { setSelectedVideo(resp.data); }); }, []); ```
  • @timohuennebeck 是的,如果您不需要在组件的其他位置使用 fetchData 函数,您也可以这样做。
猜你喜欢
  • 2020-02-14
  • 1970-01-01
  • 2020-11-20
  • 1970-01-01
  • 1970-01-01
  • 2020-06-24
  • 1970-01-01
  • 2019-12-31
  • 1970-01-01
相关资源
最近更新 更多