【问题标题】:React class method not defined no-undefReact 类方法未定义 no-undef
【发布时间】:2018-05-16 01:13:46
【问题描述】:

我是新手,我正在尝试从 randomuserapi 中提取和显示数据。我已经进行了 api 调用,但是当我运行我的应用程序时,我收到以下错误:

./src/App.js
Line 45:  'getData' is not defined  no-undef

下面是我的代码: getData() 方法是我进行 api 调用的地方。该方法现在在 ComponentDidMount 中调用。

我还将 getData() 绑定到我的构造函数,但我仍然收到上述错误。

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      people: []
 }

 this.getData = this.getData.bind(this);
}

getData() {
 const promise = fetch('https://randomuser.me/api/?results=20')
   .then(response => {
     if (response.status >= 400) {
     throw `Response Invalid ( ${response.status} )`;
     return;
   }
   return response.json();
 })
 .then(({results}) => {
   return results;
 })
 .catch(error => {
   console.log(error);
 });

 return promise;
}

ComponenDidMount() {
  getData()
    .then(data => {
      this.setState({
        people: data
      });
    });
}

render() {
  return (
    <div>
      <p>{this.state.people.results[0].gender}</p>
    </div>
  );
 }
}

export default App;

我也在使用来自 Github 的 create-react-app。请提供一些帮助。

谢谢!

【问题讨论】:

    标签: javascript reactjs api jsx


    【解决方案1】:

    在调用函数时尝试添加this.this.getData()componentDidMount

    【讨论】:

      【解决方案2】:

      当你引用定义的方法时,你需要说this 所以:

      componenDidMount() {
        this.getData()
          .then(data => {
            this.setState({
              people: data
            });
          });
      }
      

      【讨论】:

        猜你喜欢
        • 2018-02-21
        • 2020-12-21
        • 2019-11-10
        • 2019-10-05
        • 2018-03-18
        • 2022-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多