[英]Having trouble setting the state in a promise
我的componentDidMount()
函数中有一系列 promise。 在values.then(function(result)
承诺中,我正在尝试设置状态。我收到此错误Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined
but researched this error and I need to bind my promise using一个箭头函数,让它可以访问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]
})
})
})
}
问题是我不知道将箭头函数放在这种承诺上的位置。 无论我把它放在哪里,我都会收到一条错误消息,说是Unexpected token, expected "{"
,然后当我尝试放入大括号时,我又收到了另一个错误。
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)
承诺以便我可以设置状态的正确方法是什么?`
就像您使用的其他两个箭头函数一样:
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]
})
})
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.