React无法呈现状态属性

时间:2017-10-31 05:46:14

标签: javascript reactjs

我一直在犯一个类型错误:无法读取属性...... 我正在从fetch响应中将状态设置为JSON对象。对象的String和Date属性似乎正常,但Array和Number属性不断出现类型错误。

model

1 个答案:

答案 0 :(得分:2)

setState是异步的,因此您需要像这样处理this.state.post

render() {

  if (this.state.post) {
    return (<div className="Post">
      <div className="card">
        <img className="img-fluid" src="/img/darkstockphoto.jpg" alt="Post"/>
        <div className="card-body">
          <h4 className="card-title">{this.state.post.title}</h4>
          <p className="card-text">{this.state.post.author}</p>
          <p className="card-text">{this.state.post.date}</p>
          <p className="card-text">{this.state.post.body}</p>
        </div>
      </div>
      <hr/> {
        this.state.post.comments && this.state.post.comments.map(comment => (<div key={comment.author + comment.date} className="card card-body">
          <h4 className="card-title">{comment.title}</h4>
        </div>))
      }
    </div>);
  }

  return null;
}