javascript - 读取未定义的属性 'setState'

标签 javascript reactjs ecmascript-6

我试图从示例 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, or new.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, so this 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/

相关文章:

javascript - 如何在样式中使用同级选择器 css

javascript - 为什么在对象字面量定义中使用数组/大括号来允许动态计算 Javascript/ES2015 中的键?

javascript - if 语句主体高度 < 100% javascript/jquery

javascript - 如何将一个简单的 React JS 应用程序从根目录移动到子目录中?

javascript - 根据其他元素的属性设置元素样式

reactjs - 使用 Next JS 和 React 导航来响应 native Web

reactjs - 使用 React Hooks 时如何替换 this.setState?

javascript - 为什么在 Chrome 上在 `let` 循环中使用 `for` 这么慢?

javascript - 修复 iOS/iPad 2 中的溢出内容滚动

javascript - 通过 jQuery/CSS 在 for 循环内右对齐文本字段