gpt4 book ai didi

javascript - 从 axios 响应中 react 设置状态

转载 作者:行者123 更新时间:2023-12-01 01:07:56 24 4
gpt4 key购买 nike

我正在尝试使用 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/

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