gpt4 book ai didi

javascript - 在 React 中尝试访问对象的属性时如何修复 'Type Error: Cannot Read Property ' 名称'未定义'

转载 作者:行者123 更新时间:2023-11-30 19:12:14 24 4
gpt4 key购买 nike

在使用来自 a 的 promise 更新组件的状态之后 fetch 调用,我无法访问对象的属性。 当我 console.log 对象时,我看到了它,但是当我尝试访问时 它抛出类型错误的属性:无法读取属性“名称” 未定义的。
我试过 console.log(Object.keys(filteredStudents[0])) 和我
得到:
TypeError:无法将 undefined 或 null 转换为对象
类 App 扩展 React.Component { 构造函数( Prop ){ super ( Prop ) 这个。状态= { 搜索字段:'', 学生: [], 菜单:“家” }

  componentDidMount() {

fetch('https://jsonplaceholder.typicode.com/users')
.then(response => {
return response.json()
}).then(data => {
// console.log(data);
this.setState({students: data})
}).catch(err => console.log('error', err))
}

render (){
```````````````````````````````````````````````````````````
const filteredStudents = this.state.students
console.log(filteredStudents[0])
console.log(Object.keys(filteredStudents[0]))
````````````````````````````````````````````````````````
);
}

}
}

I expect the output to return the value of any key I try to
access. e.g
console.log(filteredStudents[0].name) -----> 'leanne'

最佳答案

您正试图在 promise 有机会解决之前以及您的状态更新之前访问 fiteredStudents 数组中的项目。如果您将逻辑包装在条件中,即

if(filteredStudents.length) {
console.log(filteredStudents[0])
console.log(Object.keys(filteredStudents[0]))
}

那么它应该可以工作了。

关于javascript - 在 React 中尝试访问对象的属性时如何修复 'Type Error: Cannot Read Property ' 名称'未定义',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58359720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com