我从一个看起来像这样的端点获取一个 json:
{"section":{"name":"name","subsections":[
{"name":"one","snippets":[{"title":"title","body":"body"}]},
{"name":"two","snippets":[{"title":"title","body":"body"}]}]
}}
这就是我获取数据的方式:
fetchData() {
axios.get('/api/data')
.then(response => {
this.setState({
section: response.data.section
})
})
.catch(error => {
console.log(error);
});
}
componentDidMount() {
this.fetchData();
}
但是当我打电话时,this.state.section.subsections[0]
我收到以下错误:
Uncaught TypeError: Cannot read property '0' of undefined
我知道这subsections
是一个数组,但是要从中获取元素。我得到一个错误。有谁知道我可能做错了什么?
编辑:
我想访问渲染方法中的状态。我可以访问this.state.section.name
,我也可以this.state.section.subsections
在控制台上打印。但是,每当我尝试使用访问元素时,this.state.section.subsections[0]
都会出现错误。