【问题标题】:Fetching data but "Cannot read property '0' of undefined"正在获取数据但“无法读取未定义的属性 '0'”
【发布时间】:2021-06-01 01:07:05
【问题描述】:

我尝试从 https://randomuser.me/api/ 获取一些数据。我想随机选择一个用户性别,但我不知道为什么我的函数不这样做,并且我收到此错误“无法读取未定义的属性 '0'”

我的代码:

const [fetchData, setFetchData] = useState('');
         
    fetch('https://randomuser.me/api/')
        .then((response) => response.json())
        .then(setFetchData)
        .then(console.log(fetchData.results[0].gender));

【问题讨论】:

  • 您正试图在设置后立即访问状态。 stackoverflow.com/questions/38558200/…
  • 您应该在 useEffect 中进行 API 调用。
  • @selbie 我认为是的,因为我在上一个项目中做了同样的事情并且进展顺利

标签: reactjs fetch fetch-api


【解决方案1】:

fetchData 不会在调用 setFetchData 时得到更新。请记住,它只是在您调用useState 时分配的局部变量。在下一次调用您的函数之前,它不会神奇地更新。即便如此,setState 也是异步的,因此它可能不会立即更改。

这可能是你真正想要的。

fetch('https://randomuser.me/api/')
    .then((response) => response.json())
    .then((json)=> {
         setFetchData(json);
         console.log(json.results[0].gender);
     });

我在本地尝试过,它对我有用。

另外,顺便说一句。为了稳健性,当响应完全出乎意料时,您不会在控制台语句上抛出异常:

if (json && json.results && json.results[0]) {
    console.log(json.results[0].gender);
}

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 2019-11-20
    • 1970-01-01
    • 2021-08-28
    相关资源
    最近更新 更多