在特定条件下重新触发GET请求

Retriggering a GET request React under certain conditions

本文关键字:新触发 GET 请求 条件下      更新时间:2023-09-26

我使用jquery向测验API发出GET请求。我使用React向用户显示问题,如果他们得到正确的问题,我想触发API请求并获取一个新问题。

如果用户得到正确的答案,我试图触发使GET请求的功能,但是控制台告诉我this.serverRequest is not a function

我昨天才开始学习react,所以请原谅任何可怕的错误,但也可以随时提供关于如何改进代码的反馈。

请参阅下面的代码,希望能更清楚地说明我所面临的问题。

var Quiz = React.createClass({
  getInitialState: function() {
        return {
            question: '',
            answer: '',
            score: 0
        }
  },
  checkAnswer: function(event) {
     if(event.target.value === this.state.answer) {
        this.setState({
            score: this.state.score + 1
        })
        this.serverRequest;
     }
  },
 componentDidMount: function() {
     this.serverRequest = $.get('http://jservice.io/api/random', function(data){
        var response = data[0];
        this.setState({
            question: response.question,
            answer: response.answer
        })
    }.bind(this));
 },
  render: function() {
      return (
          <div>
              <p>{this.state.question}</p>
              <input type='text' onChange={this.checkAnswer}/>
              <p>{this.state.score}</p>
          </div>
      )
  }
});

明白了!

我将get请求移动到另一个方法中,并在theComponentDidMount方法中调用它。

getData: function() { 
    $.get('http://jservice.io/api/random', function(data){
        var response = data[0];
        console.log(response)
        this.setState({
            question: response.question,
            answer: response.answer
        })
    }.bind(this));
},
componentDidMount: function() {
    this.serverRequest = this.getData()
},