开发者问题收集

React 无法渲染状态属性

2017-10-31
799

我不断收到类型错误:无法读取属性... 我正在将状态设置为来自获取响应的 JSON 对象。该对象的 String 和 Date 属性似乎呈现正常,但 Array 和 Number 属性不断收到类型错误。

class ViewPost extends Component {
    state = {
      post: {}
    }

    constructor(props) {
      super(props);
      this.setPostState = this.setPostState.bind(this);
    }

    componentWillMount() {
      this.setPostState();
    }

    setPostState() {
      let postTitle = this.props.match.params.id;
      fetch('/posts/getpost', {
        method: 'post',
        headers: {
          'Accept': 'application/json, text/plain, */*',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          title: postTitle
        })
      })
      .then(res => res.json())
      .then(post => this.setState({ post }))
    }

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

export default ViewPost;
1个回答

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;
}
Syed
2017-10-31