【问题标题】:Cannot able to push elements into the array无法将元素推入数组
【发布时间】:2019-11-28 11:26:34
【问题描述】:
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)
    });
  });
}

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

WARN 可能的未处理 Promise Rejection (id: 0): TypeError: undefined 不是对象(评估 'this.history.push')

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    我可以看到两件事可能会导致您的问题。首先,不要像这样改变状态:this.state.history.push(results.get(results[i])) 你应该总是使用this.setState 来改变状态以避免代码中的错误。

    第二次尝试将回调写成箭头函数。使用普通函数可能会更改 this 的值,所以 this.state 现在可能有所不同。

    【讨论】:

      【解决方案2】:

      首先,我认为您没有处理承诺拒绝。更改状态将使用 this.setState() 处理是最佳实践,并且状态应该像这样编写。我认为这对你有帮助

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-17
        • 1970-01-01
        • 1970-01-01
        • 2018-08-28
        • 1970-01-01
        • 2016-08-28
        • 1970-01-01
        相关资源
        最近更新 更多