在承诺中设置状态时遇到麻烦



我的componentDidMount()函数中有一系列承诺。在values.then(function(result)承诺中,我正在尝试设置状态。我Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined收到此错误,但研究了此错误,我需要使用箭头函数绑定我的承诺以使其访问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]
})
})
})
}

最新更新