使用条件时,React Component未显示

时间:2016-10-14 13:58:33

标签: javascript reactjs

我正在关注CodeSchool的React JS示例。我能够效仿这些例子。问题是当我尝试实现IF条件以将不同的数据传递给Component时。未显示的组件是“评论”。查看_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"}
    ];      
  }

有人能指出我的错误吗?

1 个答案:

答案 0 :(得分:1)

你几乎做对了,你忘了拨打comments()

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