簡體   English   中英

在onClick事件之后,React組件不會重新渲染

[英]React component wont re-render after onClick event

我有一個名為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/

render函數中包含過多的業務邏輯,這使您的代碼難以推理。 將該邏輯移動到recentalltime函數中,以便它們根據對象的alltimerecent屬性對露營者數組進行重新排序。 例如:

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

這將自動調用render函數(應該只是呈現UI元素,並且其中沒有任何邏輯)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM