使用superagent和React从API响应中获取setState

And*_*ndo 2 superagent reactjs

尝试更改组件的状态时出错.

未捕获的TypeError:无法读取未定义的属性"setState"

constructor(props){
    super(props);

    this.state={
        r:'',
        message:''
    };
    this.setStateMessage = this.setStateMessage.bind(this);
}
setStateMessage (e){
    e.preventDefault();
    var test = this.state.message;

    request
      .post('http://127.0.0.1:5000/api/db')
      .send({message: this.state.message})
      .accept('application/json')
      .withCredentials()
      .end(function(err, res){
        if(err)
            throw err;
        this.setState({ r: res.body.message });
      });
}

render() {
    return (
        <div>
            <div className='response'>
                {this.state.r}
            </div>
            //form with input
        </div>
    )}
Run Code Online (Sandbox Code Playgroud)

ara*_*y12 6

这是因为您this.setState在函数内调用,所以this实际上是对您所在函数的引用.您需要存储对正确的引用this或使用没有自己的上下文并从父上下文继承的箭头.所以:

setStateMessage (e){
  e.preventDefault();
  var test = this.state.message;
  var self = this;

  request
    .post('http://127.0.0.1:5000/api/db')
    .send({message: this.state.message})
    .accept('application/json')
    .withCredentials()
    .end(function(err, res){
      if(err) throw err;
      self.setState({ r: res.body.message });
  });
}
Run Code Online (Sandbox Code Playgroud)

要么:

setStateMessage (e){
  e.preventDefault();
  var test = this.state.message;

  request
    .post('http://127.0.0.1:5000/api/db')
    .send({message: this.state.message})
    .accept('application/json')
    .withCredentials()
    .end((err, res) => {
      if(err) throw err;
      this.setState({ r: res.body.message });
  });
}
Run Code Online (Sandbox Code Playgroud)