首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用动态类创建的ReactJS排序列

使用动态类创建的ReactJS排序列
EN

Stack Overflow用户
提问于 2018-06-02 22:48:05
回答 1查看 33关注 0票数 0

我继承了一大堆代码,它通常可以工作。它在v0.13.3上运行。

我遇到的问题是对列进行排序。每当我为下面的单击事件调用处理程序时,我都会得到一个空的this.state。我肯定遗漏了一些简单的东西,因为我已经做了很多凝视/比较其他工作代码,我只是没有看到它,但这个示例组件正在困扰我。

我已经将问题组件简化为包含静态样本数据的独立html文件:

<div id="content">Loading ...</div>
<script>
var theData = [{"id":"47483648","labName":"Lab0"},{"id":"47483650","labName":"Lab1"},{"id":"47483651","labName":"Lab2"},{"id":"47483654","labName":"Lab3"}];

function render() {
  React.render(React.createElement(aTable, {data: theData}),document.getElementById("content"));
}

var aTable = React.createClass({displayName: "aTable",
  handleHeaderClick: function(sortBy) {
      console.log("firing aTable handleHeaderClick");
      //this.state is null here
      var newState = this.state;

      if (this.state.sortBy === sortBy && this.state.sortOrder === 'asc') {
          newState.sortOrder = 'desc';
      }
      else {
          newState.sortOrder ='asc';
      }
      newState.sortBy = sortBy;

      this.setState(newState);
  },
  render: function(){
      var theItems = $.map(this.props.data, function (key, value) {
          console.log("the items", key);
          return (
              React.createElement("tr",{key: key.id + "-row"}, 
                  React.createElement("td", {key: key.agentid}, key.id),
                  React.createElement("td", {key: key.labName}, key.labName),
              )
          );
      });

      return (
          React.createElement("div", {id: "holder"},  
              React.createElement("div", {id: "a-table"}, 
                  React.createElement("table",null,
                      React.createElement("thead",null,
                          React.createElement("tr",null,
                              React.createElement("th",null," The ID"),
                              React.createElement("th",
                                  {onClick: this.handleHeaderClick.bind(this, "labName")},
                                  "Lab Name")
                              )
                          ),
                      React.createElement("tbody",null,
                          theItems
                      )
                  )
              )
          )
      );
  }
});


$(document).ready(function () {

  render();
});

这会在null状态上抛出一个异常:

basic.html:37 Uncaught TypeError: Cannot read property 'sortBy' of null

它指的是这一行:

if (this.state.sortBy === sortBy && this.state.sortOrder === 'asc') {

我有更改处理程序逻辑的自由,但目前仍坚持这种模式。

提前谢谢。

EDIT 1这是一个有效的小提琴,在Sy指出我缺少初始状态的地方后,我通过对数据数组进行字段排序来进行排序:working fiddle

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50658071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档