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

Method not updating state when called in componentDidMount()

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

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

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

(2) this.state.totalDonations: 0
(2) now need to set state to: 4205

使用箭头函数保留 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 })
  })
}

希望这会有所帮助!