【发布时间】:2019-06-03 05:58:58
【问题描述】:
我知道对此有很多答案,例如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;
【问题讨论】:
标签: reactjs