2017-10-31 4 views
0

タイプエラーが発生し続ける:プロパティを読み取れません... フェッチ応答から状態をJSONオブジェクトに設定しています。オブジェクトのStringプロパティとDateプロパティはうまく表示されているようですが、ArrayプロパティとNumberプロパティは引き続きタイプエラーが発生します。Reactは状態プロパティをレンダリングできません

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; 
+0

https://stackoverflow.com/questions/47027035/why-is-my-react-この回答を参照してください。コンポーネント - この状態更新スクリプト - 不定 - 偶数 -/47028520#47028520また、this.state.postが空であるため、初めに 'this.state.post.title'と他のものを条件付きでコメントのためにレンダリングするのも理にかなっています –

答えて

1

あなたはこのようなあなたのthis.state.postを処理する必要があるので、SETSTATEは、非同期です:

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; 
} 
+0

完全な説明ではありません。コメントに追加した回答へのリンクを参照してください –

関連する問題