【问题标题】:API response is undefined when used, but not when console.log()API 响应在使用时未定义,但在 console.log() 时未定义
【发布时间】:2021-07-05 09:45:11
【问题描述】:

我正在尝试显示来自https://api.coincap.io/v2/assets 的数据。 我在控制台中获取数据,但是当我尝试在 return() 中显示它时,数据变得未定义。

TypeError: Cannot read property '0' of undefined


    useEffect(() => {
        axios.get('https://api.coincap.io/v2/assets')
            .then(function (response) {
                setApiData(response.data.data)
                //console.log(response.data.data);
            })
            .catch(function (error) {
                console.log(error);
            })
    }, [])

console.log(apiData)
    return (
        <>
            {/*{apiData[0].id}*/}
        </>
    )
};

我认为是useEffect需要在页面渲染后再次运行?

【问题讨论】:

  • 状态挂钩(在您的示例中为 setApiData())是 异步的 - 它不会立即设置。

标签: reactjs api axios undefined use-effect


【解决方案1】:

首先你应该检查你的数组是否有数据。顺便我没查代码,应该是这样的。

return (
    <>
      {apiData && apiData.length !== 0 ? apiData[0].id : "Please wait while fetching..."}
    </>

【讨论】:

  • 谢谢!这行得通,你能解释为什么检查数组是否有数据使它工作吗?
  • 正如@Jax-p 在您的问题评论部分中提到的,您的“axios.get”方法是异步的。所以当你渲染你的页面时,'apiData[0].id' 还没有被获取,因为异步方法需要一些时间来从网络获取数据。我们把 'apiData && apiData.length' 控件的意思是“如果我有 apiData 数组并且这个数组的长度不等于零,则在页面 apiData[0].id 上渲染”。
  • 顺便说一下,请检查我的消息作为正确答案,以便其他用户可以从中获得帮助。
  • 谢谢!我打算去,但stackoverflow有一个计时器,所以我不得不等待。 @shadowman_93
猜你喜欢
  • 2020-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-28
  • 2020-04-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多