javascript - 无法使用 axios 设置状态
问题描述
componentDidMount() {
var self = this;
axios.get('http://URL')
.then(function (response) {
console.log(response.data);
this.setState({
data: response.data
})
})
.catch(function (error) {
console.log(error);
});
}
我收到此错误:TypeError: Cannot read property 'setState' of undefined
解决方案
使用箭头函数,这样你就不需要依赖局部变量了,作用域会被自动处理
componentDidMount(){
axios.get('http://URL')
.then( response => {
console.log(response.data);
this.setState({data: response.data})
})
.catch(error => {
console.log(error);
});
}
或者在执行 setState 时将其替换为 self ,如下所示
componentDidMount(){
var self = this;
axios.get('http://URL')
.then(function (response) {
console.log(response.data);
self.setState({data: response.data})
})
.catch(function (error) {
console.log(error);
});
}
以上两个选项都可以。我建议你选择第一个选项
推荐阅读
- php - 如何在 laravel 5.6 刀片中获取计数值?
- ios - Swift 4.2 - 如何在枚举函数中使用警报?
- angularjs - 执行 CORS 时自定义标头不可用
- android - Recyclerview滚动缓慢并卡住android
- ios - 在我的应用程序中点击 UITextField 时没有出现 UIKeyboard
- styles - 如何制作mapbox数字风格
- android - 使用 android 具有悬停效果的 Google geojsonlayer 多边形
- checkbox - 复选框大小 Xamarin Android
- javascript - 如何使用 Browserify?
- linux - 确定第一个内存地址