Storing nested objects in React State

2019-08-24 08:58发布

问题:

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();
}

But when I call this.state.section.subsections[0] I get the following error:

Uncaught TypeError: Cannot read property '0' of undefined

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?

Edit:

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.

回答1:

You might be trying to access data before it's available,

Try this :

this.setState({
    section: response.data.section
},() => {
    console.log('After state set :' ,this.state.section.subsections[0]);
});

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


First Solution :

Provide default empty array from render

render(){
   const subsections = this.state.section.subsections || [];
   return(...)
}

Second Solution :

Provide default empty array from reducer as initial state



回答2:

Uncaught TypeError: Cannot read property '0' of undefined occurs when you try to retrieve a property from an undefined variable.

Essentially, the console is trying to tell you that this.state.section.subsections == undefined, therefore you cannot call for undefined[0].

You might want to check whether or not this.state.section.subsections exists before polling it for variables.

ie.

if (this.state.section.subsections) {

  // Exists.
  console.log(this.state.section.subsections)

} else {

  // Undefined.
  console.log(this.state.section.subsections)

}