我正在尝试使用 axios POST 调用返回的信息更新状态。我收到一条错误消息 TypeError: Cannot read property 'setState' of undefined
。在我看来,this
无法从 API 响应中使用。
submitData= () => {
axios.post("url", this.props.data)
.then(function (result) {
console.log(result,'success');
this.setState({
...this.state,
id: result.data.id
})
})
.catch(function (err) {
console.log(err, 'fail');
});
}
我可以控制台日志result.data.id
,它是正确的ID。我在所有客户端都这样做,我不想构建服务器或使用 reducer 。
最佳答案
在回调中使用箭头函数,如下所示:
submitData= () => {
axios.post("url", this.props.data)
.then((result) => {
console.log(result,'success');
this.setState({
...this.state,
id: result.data.id
})
})
.catch(function (err) {
console.log(err, 'fail');
});
}
关于javascript - 从 axios 响应中 react 设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55445484/