在onClick事件之后,React组件不会重新渲染

时间:2016-03-20 19:49:11

标签: javascript reactjs

我有一个名为CamperList的React组件,它呈现一个表行组件数组。其中两个表头标签有onClick事件,它们应该切换this.state.toggle并更新表。当我单击“所有时间点”标记时,表格会更新,但是当我在过去30天内点击“标记”标记时,它将无法更新。这是代码:

var CamperList = React.createClass({
 getInitialState: function() {
  return {
   recent: [],
   toggle: true
  };
 },
 componentDidMount: function() {
  $.get('http://fcctop100.herokuapp.com/api/fccusers/top/recent', function(data) {
      this.setState({
       recent: data
      });
    }.bind(this));
  },
 recent: function() {
  this.setState({toggle: true});
 },
 alltime: function() {
  this.setState({toggle: false});
 },
 render: function() {
  var camperNodes;
  if (this.state.toggle) {
   camperNodes = this.state.recent.map(function(camper, index) {
      return (
        <Camper index={index + 1} username={camper.username} recent={camper.recent} alltime={camper.alltime} />
      );
    });
  } else {
   var alltime = this.state.recent;
   alltime = alltime.sort(function(a,b) {
        return b.alltime - a.alltime;
       })
   camperNodes = alltime.map(function(camper, index) {
      return (
        <Camper index={index + 1} username={camper.username} recent={camper.recent} alltime={camper.alltime} />
      );
    });
  }
    return (
     <table className="table">
      <thead className="blue">
      <tr>
        <th>#</th>
        <th>Camper Name</th>
        <th onClick={this.recent}>Points in past 30 days</th>
        <th onClick={this.alltime}>All time points</th>
      </tr>
      </thead>
    <tbody>
     {camperNodes}
    </tbody>
   </table>
    );
  }
});

指向笔的链接:http://codepen.io/ZacharyKearns/pen/dMvGNG/

1 个答案:

答案 0 :(得分:0)

您的render函数中包含太多业务逻辑,这使您的代码难以推理。将该逻辑移入recentalltime函数,以便根据对象重新排序露营者阵列。 alltimerecent属性。例如:

alltime: function() {
   var sortedArr = [];
   //sort the array from highest alltime to lowest
   this.setState({
       recent: sortedArr
   })
}

这会自动调用渲染函数(它应该只渲染UI元素而不包含任何逻辑)。