【发布时间】: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 我认为是的,因为我在上一个项目中做了同样的事情并且进展顺利