reactjs - 未处理的拒绝(TypeError):无法读取未定义的属性“setState”
问题描述
我知道对此有很多答案,例如this one。我确实.bind(this)
在组件构造函数中添加了。我也尝试了粗箭头方法 ( fakeApiCall = ()=>{ ... }
),但是当我单击 时Change Me
,仍然显示此错误:
import React, { Component } from 'react';
import axios from 'axios';
class App extends Component {
constructor(props){
super(props);
this.state = {
count : 1000
};
this.fakeApiCall = this.fakeApiCall.bind(this);
}
fakeApiCall (){
axios.get('https://jsonplaceholder.typicode.com/users')
.then(function(response){
// the response comes back here successfully
const newCount = response.data.length;
// fail at this step
this.setState({ count : Math.floor(newCount) });
});
}
render() {
return (
<div className="App">
<span style={{ fontSize : 66 }}>{this.state.count}</span>
<input type='button' onClick={this.fakeApiCall} value='Change me' />
</div>
);
}
}
export default App;
解决方案
您的fakeApiCall
函数绑定到您的上下文,但函数回调axios
不是。
为了解决这个问题,您可以使用箭头函数,因为它们会自动与您的类绑定。您也可以这样做fakeApiCall
并删除它的绑定:
class App extends Component {
constructor(props) {
super(props);
this.state = {
count: 1000
};
}
fakeApiCall = () => {
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => { //This is an arrow function
const newCount = response.data.length;
this.setState({ count: Math.floor(newCount) });
});
}
render() {
return (
<div className="App">
<span style={{ fontSize: 66 }}>{this.state.count}</span>
<input type='button' onClick={this.fakeApiCall} value='Change me' />
</div>
);
}
}
推荐阅读
- reactjs - React-如何根据父状态更新子道具
- laravel - Laravel 中的 attributesToArray() 和 toArray() 有什么区别?
- docker - 主机名不适用于 docker swarm 模式
- android - Android.Views.InflateException: Binary XML file line #1: Binary XML file line #1: Error inflating class android.support.design.widget.NavigationView
- mysql - 如何在我的视图 mysql 中更改和添加“id”列
- c# - Linq Select 作为循环条件 C#
- aws-sam - 无法使用 Sub 函数指定 x-amazon-apigateway-integration uri
- datagrid - 是否可以在 Jboss 数据网格中使用像复杂查询这样的存储过程?
- cocos2d-x - Cocos2d-x 场景移动和不正确的物理调试绘制
- python - 如何在 Django view.py 中获得如下结构的 Html-Ajax 后数组值?