javascript - 如何访问嵌套在 React 状态数组中的对象中的元素?
问题描述
我正在学习React,今天遇到了一个问题。我试图从 api 获取数据,一切都很顺利,直到我将“字符”从对象更改为数组。之后,我的 jsx 不再可以访问状态中的元素。
原代码片段如下:
//When the state 'character' is an object
class Api extends React.Component {
state = {
loading: false,
character: {}
}
componentDidMount() {
this.setState({ loading: true });
fetch('https://swapi.co/api/people/1')
.then(response => response.json())
.then(data => {
this.setState(
{
character: data,
loading: false
}
);
console.log('newstate', this.state.character);
});
}
render() {
return (
<div><h3>Name: {this.state.character.name}</h3>
</div>
)
}
}
后来我想改进数据结构,所以我把'character'状态改成了一个Array,据此我改变了访问'character'的方式,结果它不再起作用了。
// after I changed the type of 'character'
class Api extends React.Component {
state = {
loading: false,
character: []
}
componentDidMount() {
this.setState({ loading: true });
fetch('https://swapi.co/api/people/1')
.then(response => response.json())
.then(data => {
this.setState(
{
character: this.state.character.concat(data),
loading: false
}
);
console.log('newstate', this.state.character);
});
}
render() {
return (
<div><h3>Name: {this.state.character[0].name}</h3>
</div>
)
}
}
我不知道如何解决这个问题。
解决方案
它与对象一起工作,因为您尝试访问对象上不存在的属性,undefined
而是得到了
当您尝试在 http 请求完成之前访问数据时,当您尝试访问属性array[0]
时undefined
会抛出错误undefined
有几种方法可以使它工作,当使用数组时,您可以映射数组并渲染元素,如果数组为空,则不会渲染任何内容
<div>
{this.state.character.map(char => (
<h3 key={char.name}>Name: {char.name}</h3> // don't forget the key
)}
</div>
如果您只想呈现第一个元素,您还可以在尝试访问元素上的属性之前检查数组中是否有元素
<div>
{this.state.character[0] && (
<h3>Name: {this.state.character[0].name}</h3>
)}
</div>
但是,看起来您在数组中存储了一个字符,将其保留为一个对象是有意义的,当您需要存储多个项目而不是一个项目时使用数组
推荐阅读
- mysql - 迁移到微服务 - mysql
- python - 局部变量和 elif
- python - 如何通过python中的代理硒访问国家限制网站
- java - button.OnClick 代码运行但不执行更改?
- python - Kivy 自动调整按钮和标签以适应屏幕
- routes - 在中间件中将 GET 更改为 POST - SLIM Framework 3
- javascript - 更改 CSS3 动画的开始
- javascript - Can I fetch a Readable Stream then convert to JSON client side?
- jsf - PanelBox 公开的属性不起作用
- macos - 如何动画关闭 NSWindow 到 NSStatusItem?