正在获取数据但 "Cannot read property '0' of undefined"
Fetching data but "Cannot read property '0' of undefined"
我尝试从 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));
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);
}
我尝试从 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));
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);
}