gpt4 book ai didi

javascript - 在 promise 中设置状态时遇到困难

转载 作者:行者123 更新时间:2023-12-02 22:05:42 25 4
gpt4 key购买 nike

我的 componentDidMount() 函数中有一系列 promise 。在 values.then(function(result) promise 中,我尝试设置状态。我收到此错误 Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined 但研究了这个错误,我需要使用箭头函数绑定(bind)我的 Promise,以使其能够访问 this 关键字。

componentDidMount() {
let general = {};
let values = [];
//gets selected setting form schema
getSettingsForms().then((response) => {
this.setState({settingsForms: response});
general = response[this.state.selectedSetting];
}).then(response => {
values = getSettingsConfig(this.state.selectedSetting, general);
values.then(function(result) {
this.setState({
formSchema: result[1],
selectedSetting: this.state.selectedSetting,
settings: result[0]

})

})
})
}

问题是我不知道在哪里把箭头函数放在这种 promise 上。无论我把它放在哪里,我都会收到一条错误消息,指出意外的标记,预期为“{”,然后当我尝试放入大括号时,我收到另一个错误。

componentDidMount() {
let general = {};
let values = [];
//gets selected setting form schema
getSettingsForms().then((response) => {
this.setState({settingsForms: response});
general = response[this.state.selectedSetting];
}).then(response => {
values = getSettingsConfig(this.state.selectedSetting, general);
values.then(function(result) => {
this.setState({
formSchema: result[1],
selectedSetting: this.state.selectedSetting,
settings: result[0]

})

})
})
}

将此箭头函数放入 values.then(function(result) Promise 以便我可以设置状态的正确方法是什么?`

最佳答案

就像您使用的其他两个箭头函数一样:

componentDidMount() {
let general = {};
let values = [];
//gets selected setting form schema
getSettingsForms().then((response) => {
this.setState({settingsForms: response});
general = response[this.state.selectedSetting];
}).then(response => {
values = getSettingsConfig(this.state.selectedSetting, general);
values.then(result => {
this.setState({
formSchema: result[1],
selectedSetting: this.state.selectedSetting,
settings: result[0]

})

})
})
}

关于javascript - 在 promise 中设置状态时遇到困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59720522/

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