constructor(){
super();
this.state = {
data: ''
}
}
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
this.setState({data: response }); // here i am getting error
console.log(this.state.data);
})
.catch(function (error) {
console.log(error);
});
在我的React本地应用中,我无法设置Ajax响应。.当我尝试更新状态时,它会引发错误并执行捕获功能...我不知道为什么会发生它可以给您提供我快速建议
首先,请阅读箭头函数和正常函数声明之间的差异。
this.setState({})
仅在使用箭头函数() =>
时才能使用,或者可以通过将this
保存在类似的变量中,以旧的时尚方式进行操作:
fetchData() {
const self = this;
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
self.setState({data: response }); // here i am getting error
console.log(self.state.data);
})
.catch(function (error) {
console.log(error);
});
}
但是,i更喜欢使用箭头功能,因为它更简单。
ex:
fetchData() {
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(response => this.setState({data: response }) )
.catch(console.log);
}
P.S:您也可以使用.bind(this)
方法绑定this
。
这是因为您使用ES2015语法来创建您的函数,默认情况下不会绑定上下文。改用箭头功能:
.then((reponse) => {
console.log(response);
this.setState({data: response });
console.log(this.state.data);
}