setState无效

时间:2017-07-20 15:58:01

标签: reactjs

class Assets extends React.Component{

  constructor() {
    super();
    this.state = {
          assets: [],
          secondsElapsed: 0
        };
    }

tick() {
    if(start === true){

      fetch('/api/user/all/?name='+name, {credentials: 'include', method: 'get'}).then(function(data){
        return data.json();
      }).then( json => {
        this.setState({
            assets: json
          });
      });
      }
    }
  }

ReactDOM.render(<Assets />, document.getElementById('alerts'));

此代码在运行时抛出此错误:

Uncaught (in promise) TypeError: Cannot read property 'setState' of null
    at eval (eval at <anonymous> (bundleAlerts.js:3430), <anonymous>:265:15)
    at <anonymous>

如果这会产生影响,那么代码就会被webpack编译。我之前使用的是ReactCreate类,它工作正常,但我更改了它以尝试修复另一个错误。

谢谢,Ed。

1 个答案:

答案 0 :(得分:2)

tick功能绑定到您的组件。 :)它当前绑定到函数而不是类组件,因此它无法访问“this”,这意味着它将无法访问您的props或state。您可以使用下面的示例,autobind装饰器(ES7)或转换类属性'tick =()=&gt; {...}'。

&#13;
&#13;
class Assets extends React.Component {
  constructor() {
    super();
    this.state = {
      assets: [],
      secondsElapsed: 0
    };
    this.tick = this.tick.bind(this);
  }
  tick() {
    if (start === true) {
      fetch("/api/user/all/?name=" + name, {
        credentials: "include",
        method: "get"
      })
        .then(data => {
          return data.json();
        })
        .then(json => {
          this.setState({
            assets: json
          });
        });
    }
  }
  // ...rest of component
}

ReactDOM.render(<Assets />, document.getElementById("alerts"));
&#13;
&#13;
&#13;