ReactJS如何排序列创建动态类?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (109)

我已经继承了一大堆代码,它通常工作。这在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') {
提问于
用户回答回答于

statenull因为你没有设定初始值。

Test = React.createClass({
  getInitialState: function() {
    return {};
  }
})

这相当于

class Test extends Component {
  constructor(props) {
    this.state = {}
  }
}

扫码关注云+社区

领取腾讯云代金券