在 React State 中存储嵌套对象 [英] Storing nested objects in React State
问题描述
我从如下所示的端点获取 json:
I'm getting a json from an endpoint which looks like this:
{"section":{"name":"name","subsections":[
{"name":"one","snippets":[{"title":"title","body":"body"}]},
{"name":"two","snippets":[{"title":"title","body":"body"}]}]
}}
这是我获取数据的方式:
This is how I get the data:
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]
时,我收到以下错误:
But when I call this.state.section.subsections[0]
I get the following error:
Uncaught TypeError: Cannot read property '0' of undefined
我知道 subsections
是一个数组,但要从中获取元素.我收到一个错误.有谁知道我可能做错了什么?
I know that the subsections
is an array, but on getting the elements from it. I get an error. Would anyone know what I might be doing wrong?
我想访问渲染方法中的状态.我可以访问this.state.section.name
,也可以在控制台打印this.state.section.subsections
.但是每当我尝试使用 this.state.section.subsections[0]
访问元素时,我都会收到错误消息.
I want to access the state in the render method. I can access this.state.section.name
, I can also print this.state.section.subsections
on the console. But whenever I try to access the elements using this.state.section.subsections[0]
I get an error.
推荐答案
您可能试图在数据可用之前访问它,
You might be trying to access data before it's available,
试试这个:
this.setState({
section: response.data.section
},() => {
console.log('After state set :' ,this.state.section.subsections[0]);
});
如果您在此处获得 console.log
,则问题如我上面所述,如果没有,则需要 console.log(this.state.section)
并检查输出
If you get the console.log
here , the issue is as I explained above , and if not then you need to console.log(this.state.section)
and check the output
第一个解决方案:
从渲染中提供默认的空数组
Provide default empty array from render
render(){
const subsections = this.state.section.subsections || [];
return(...)
}
第二种解决方案:
提供来自reducer的默认空数组作为初始状态
Provide default empty array from reducer as initial state
这篇关于在 React State 中存储嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!