Reactjs 无法将元素推入数组

Reactjs 无法将元素推入数组,reactjs,Reactjs,我无法在执行时将元素推入数组,上面的程序给出以下错误 警告可能未处理的承诺拒绝id:0:TypeError: undefined不是计算“this.history.push”的对象 我发现有两件事会引起你的问题。首先,不要像这样改变状态:this.state.history.pushresults.getresults[i]您应该始终使用this.setState更改状态,以避免代码中出现错误 其次,尝试将回调函数作为箭头函数写入。使用normal函数可能会改变this的值,因此this.sta

我无法在执行时将元素推入数组,上面的程序给出以下错误

警告可能未处理的承诺拒绝id:0:TypeError: undefined不是计算“this.history.push”的对象


我发现有两件事会引起你的问题。首先,不要像这样改变状态:this.state.history.pushresults.getresults[i]您应该始终使用this.setState更改状态,以避免代码中出现错误


其次,尝试将回调函数作为箭头函数写入。使用normal函数可能会改变this的值,因此this.state现在可能有所不同

首先,我认为你没有处理拒绝承诺的问题。更改状态将处理此问题。setState是最佳做法,状态应这样书写。我想这对你会有帮助的

state = { driverid: '', history: [{}] }

constructor(props) {
  super(props);
}

componentDidMount(){

  this.setState({ driverid: this.props.navigation.getParam('driverid', 'NO-ID') }, 
   () => {
    const GameScore = Parse.Object.extend("Booking");
    const query = new Parse.Query(GameScore);
    query.equalTo("driverid", this.state.driverid);
    query.find().then(function (results) {
      console.log("Successfully retrieved " + results.length + " scores.");

      for (var i = 0; i <= results.length; i++) {
        this.state.history.push(results.get(results[i]))
      }
      console.log(this.state.history)
    });
  });
}
constructor(props) {
  super(props);
  this.state = { driverid: '', history: [{}] }
}


query.find().then((results) => {
  console.log("Successfully retrieved " + results.length + " scores.");

  for (var i = 0; i <= results.length; i++) {
    this.setState({history:this.history.push(results.get(results[i]))})
  }
  console.log(this.state.history)
}).catch((error)=>console.log(error);