【发布时间】:2017-10-17 07:51:49
【问题描述】:
我从一个看起来像这样的端点获取 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] 访问元素时,我都会收到错误消息。
【问题讨论】:
-
您正在获取
componentDidMount中的数据并在哪里访问它?因为componentDidMount是最后一个被执行的生命周期钩子。为什么不尝试获取componentWillMount中的数据? -
我在 render() 方法中访问它。
-
componentDidMount在render方法之后被调用。尝试获取componentWillMount中的数据,它可以工作。 -
@Nandu 我试过了。没用。我刚刚编辑了问题,请看一下。
-
很高兴它成功了!
标签: reactjs ruby-on-rails-5 webpacker