gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:10:55 25 4
gpt4 key购买 nike

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

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 回调更改为(结果) => {...}。喜欢

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

希望这会有所帮助!

关于javascript - 在 componentDidMount() 中调用时方法不更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52429569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com