在componentDidMount()中调用时方法未更新状态

时间:2018-09-20 16:35:31

标签: javascript reactjs parse-server

我不知道为什么这段代码没有更新状态。我调用一个运行良好并返回值的云代码方法。您可以在代码后的控制台输出中看到这一点。

2018-09-20T16:27:18.292Z ERROR [lib/handler.js] uncaughtException: The "peer.address" program argument must be set to a legitimate value of <host>:<port>

这是控制台中记录的内容:

export class Donations extends React.Component {
  constructor() {
    super()

    this.state = {
      totalDonations: 0
    }

    this.getDonations = this.getDonations.bind(this)
  }

  getDonations = () => {
    // Total money donated to Organization for all time
    Parse.Cloud.run('donations', {}).then(function(result) {
      console.log('now need to set state to: ' + result)
      this.setState({ totalDonations: result })
    })
  }

  componentDidMount() {
    // Get data for current Organization (based on User)
    this.getDonations()
  }

  render() {
    const { totalDonations } = this.state
    console.log('this.state.totalDonations: ' + totalDonations)

    return (
      <div></div>
    )
  }
}

export default Donations

1 个答案:

答案 0 :(得分:1)

使用箭头功能保留this参考。然后将.then回调更改为 (result) => {...}。喜欢

getDonations = () => {
  // Total money donated to Organization for all time
  Parse.Cloud.run('donations', {}).then( (result) => {
  console.log('now need to set state to: ' + result)
  this.setState({ totalDonations: result })
  })
}

希望这会有所帮助!