2016-10-14 8 views
0

私はCodeSchoolのReact JSの例に従っています。私はその例に従うことができました。問題は、異なるデータをコンポーネントに渡すIF条件を実装しようとするときです。表示されていないコンポーネントは「コメント」です。 _getCommentsの機能を調べてください。 If条件を使用すると、フィドル:https://jsfiddle.net/joelgb/vxtkpzog/15/を参照して、どの配列が渡されるかを決めるために、コードは機能しません。しかし、単にIfなしで以下のコードを記述すると、コンポーネントコメントが正しく表示されます。条件を使用すると反応成分が表示されない

const commentsList = [ 
     {id: 1, author: "author1", body: "body1"}, 
     {id: 2, author: "author2", body: "body2"}, 
     {id: 3, author: "author3", body: "body3"} 
    ]; 

この方法を使用すると機能しません。

var commentsList; 
    if (a=='a'){ 
    commentsList = [ 
     {id: 1, author: "author1", body: "body1"}, 
     {id: 2, author: "author2", body: "body2"}, 
     {id: 3, author: "author3", body: "body3"} 
    ]; 
    } 
    else 
    { 
    commentsList = [ 
     {id: 1, author: "author4", body: "body4"}, 
     {id: 2, author: "author5", body: "body5"}, 
     {id: 3, author: "author6", body: "body6"} 
    ];  
    } 

誰かがエラーを指摘できますか?あなたは、ほぼ右のそれを得た

+0

'alert(JSON.stringify(commentsList));' –

答えて

1

、あなたはこの

class CommentBox extends React.Component{ 
    render() { 
     const comments = this._getComments.bind(this,'a'); 
     return (
     <div> 
      <h3>Comments</h3> 
      {comments} // <--- You are not calling comments 
      <button onClick={this._getComments.bind(this,'b')}>north</button> 
     </div>   
    ); 
    } 
    ... 
} 

class CommentBox extends React.Component{ 
    render() { 
     const comments = this._getComments.bind(this,'a'); 
     return (
     <div> 
      <h3>Comments</h3> 
      {comments()} 
      <button onClick={this._getComments.bind(this,'b')}>north</button> 
     </div>   
    ); 
    } 
    ... 
} 

your jsfiddle

A better solution using state

でなければなりません comments()

に電話をするのを忘れました

+0

私は州を忘れています。ありがとう、それは完璧に動作します。 – Joel

関連する問題