[英]React setting state from an axios response
我试图用从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。
在您的回调中使用arrow函数,如下所示:
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');
});
}
您还可以使用async / await语法并将数据作为参数传递,以提高灵活性/可重用性。 尝试:
submitData = async (data) => {
try {
const result = await axios.post('url', data);
console.log('Success', result);
const { id } = result.data;
this.setState({
...this.state,
id,
});
} catch (err) {
console.log('Failure', err);
}
}
尝试将.then
设为匿名函数来绑定this
。
submitData= () => {
axios.post("url", this.props.data)
.then((result) => {
console.log(result,'success');
this.setState({
...this.state,
id: result.data.id
})
})
.catch((err) => {
console.log(err, 'fail');
});
}
在回调函数this
将是不确定的(这就是如何this
JS中的作品)。 如果您想轻松修复,只需使用箭头功能
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');
});
}
进一步了解this
https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.