Метод не обновляет состояние при вызове в componentDidMount () - PullRequest
0 голосов
/ 20 сентября 2018

Я не могу понять, почему этот код не обновляет состояние.Я вызываю метод облачного кода, который работает нормально и возвращает значение.Это можно увидеть в выводе консоли после кода.

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

1 Ответ

0 голосов
/ 20 сентября 2018

Используйте функцию стрелки, чтобы сохранить ссылку 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 })
  })
}

Надеюсь, это поможет!

...