React: Cannot access index of an array in a state (index undefined)

匿名 (未验证) 提交于 2019-12-03 08:30:34

问题:

I have an array as a state property in my component, like this:

this.state = { postData: [{id: 1, author: 'Mary'}, {id:2, author: 'John'}] } 

When I access it through console.log, such as this.state.postData[0], it shows the contents of the object and works correctly

But when I try to output it as a content of an element, this way:

<p>{this.state.postData[0].author}</p> 

It says that this.state.postData[0] is undefined. I so far have not been able to find out why it happens, is there some special way to access arrays in React?

EDIT: Additional info and context

Initialization of the state:

constructor() {      super();      this.state = { postData: '', end : '' };      this.loadPosts = this.loadPosts.bind(this);  } 

I am loading data, using AJAX, jQuery, this is the structure of the array that contains post information: (index.js)

app.get('/requestPost/12', (req, res) => {     var jsonPosts = { posts: [ {id:1, author: 'Mary', content: 'Hello, I am Mary'} ] };     res.send(jsonPosts); }); 

Then it is received and postData state now contains the posts array.

loadPosts() {      $.get('/requestPost/12').success( (data) => {          this.setState({postData : data.posts });      });  }  componentWillMount() {      this.loadPosts();  } 

Render function. I noticed an occurence that when I display the this.state.postData[0] in console without trying to output it as the elements, it works. However, when I try to use it as an output, as <p>{this.state.postData[0].author}</p>, it stops working in the console, too. Also, it does not work when I try to display in the console a property of the postData, like console.log(this.state.postData[0].author)

render() {      console.log(this.state.postData[0]);      return (      <div>         <h1>This is the blog we all like</h1>         <p>{this.state.postData[0].id}</p>         <p>{this.state.postData[0].author}</p>         <p>{this.state.postData[0].content}</p>         <hr/>     </div>        );  } 

Thank you

回答1:

You should change initial state., you need set postData as empty Array with first element as Object, because you are trying to get first element from postData but gets undefined(this.state.postData[0] returns undefined) because it is empty String that doesn't/can't have Object as a first element

this.state = {    postData: [{ }],    end : ''  }; 

Example

Also you are using componentWillMount(triggers before render) with AJAX call, but this method does not wait while ajax will be completed. Lifecycle for your application looks like this

  1. call componentWillMount
  2. call render
  3. ajax was completed
  4. set new state
  5. call render with new state


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!