我试图从示例 api 获取数据,但不断收到错误:
Cannot read property 'setState' of undefined.
谁能告诉我为什么我收到未定义的错误,我需要绑定(bind)到这个吗?
import React, { Component } from 'react';
import axios from 'axios';
import logo from './logo.svg';
import './App.css';
import '../node_modules/bootstrap/dist/css/bootstrap.css';
import '../node_modules/bootstrap/dist/css/bootstrap-theme.css';
import Users from './components/Users.js';
class App extends Component {
constructor(props) {
super(props);
this.state = {users: []};
}
getUsers(){
axios.get('http://jsonplaceholder.typicode.com/users')
.then(function (response) {
this.setState({ users: response.data });
})
.catch(function (error) {
console.log(error);
});
}
componentDidMount(){
this.getUsers();
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<Users data={this.state.users} />
</div>
);
}
}
export default App;
最佳答案
发生这种情况是因为 this
是回调范围内的不同对象。这就是为什么它提示 setState()
不存在 - 这是错误的对象。
最简单的解决方案是所谓的箭头函数。这解决了您的问题的原因是因为箭头函数与传统函数不同,不绑定(bind) this
对象。因此,回调中的 this
对象是“正确”的,您可以调用 setState()
。
这是 MDN 文档中关于 arrow functions 的内容。 :
An arrow function expression has a shorter syntax than a function expression and does not bind its own
this
,arguments
,super
, ornew.target
. These function expressions are best suited for non-method functions, and they cannot be used as constructors.
和
An arrow function does not create its own
this
context, sothis
has its original meaning from the enclosing context.
所以你的函数将变成:
getUsers(){
axios.get('http://jsonplaceholder.typicode.com/users')
.then((response) => {
this.setState({ users: response.data });
})
.catch((error) => {
console.log(error);
});
}
catch
不需要更改,因为您只登录到控制台并且不使用 this
对象 - 但为了保持一致性,我还是更改了它。
关于javascript - 读取未定义的属性 'setState',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43091391/