javascript - React 组件在 onClick 事件后不会重新渲染

标签 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/

最佳答案

您的 render 函数中包含太多业务逻辑,这使得您的代码难以推理。将该逻辑移至 recentalltime 函数中,以便它们根据对象的 alltime 重新排序 Camper 数组最近的属性。例如:

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

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

关于javascript - React 组件在 onClick 事件后不会重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36118687/

相关文章:

reactjs - 如何在react Js中从服务器位置下载文件

reactjs - React Router NavLink不触发history.listen()函数

javascript - 设置传递给函数参数的对象属性的默认值

javascript - Next.js 加载 &lt;script&gt; 标签但不执行它们

javascript - 拖到屏幕外时如何将div拖回第一个位置

javascript - OAuth,request_token 上的 403 响应错误

javascript - AngularJS UI 路由器 : add variable to scope of state without specifying it in URL

javascript - 对象数组的复合排序(排序)

javascript - 根据 Javascript 中的列表从 Json 中提取字段

reactjs - 如何为无状态 React 组件创建 TypeScript 类型定义?