使用 superagent 和 React 从 API 响应中设置状态

setState from an API response using superagent and React

我在尝试更改组件状态时遇到错误。

Uncaught TypeError: Cannot read property 'setState' of undefined

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>
    )}

这是因为您是从函数内部调用 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 });
  });
}

或者:

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 });
  });
}

要添加到@aray12 的答案,您也可以绑定回调。

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 });
  }).bind(this));
}

在这上面花了太多时间后,我的最终代码在这里

class Data extends React.Component{

     constructor(){
        super()
        this.state={
            name:''
        }
    }

    componentDidMount(){
        console.log('componentDidMount');

        var url = "http:\//localhost:3000/order/test";
        Request
        .get(url)
        .query(null)
        .set('Accept', 'application/json')
        .end ((error, response)=>{
            const title=response.text
            console.log(JSON.stringify(title));

            this.setState({
              name:title
            });
        });

    }

    render(){
        return <div>World {this.state.name}</div>;
    }

}

注意: 如果响应是文本,你必须使用 response.text,就像我在我的案例中使用的那样

如果您想了解更多详情click here