[英]React class method not defined no-undef
I'm new to react and I'm trying to pull and display data from randomuserapi. 我是新来的反应者,我正在尝试从randomuserapi中提取并显示数据。 I've made the api call but when I run my app, I get the error below:
我进行了api调用,但是当我运行我的应用程序时,出现以下错误:
./src/App.js
Line 45: 'getData' is not defined no-undef
Here's my code below: The getData() method is where I make the api call. 这是下面的代码:getData()方法是我进行api调用的地方。 That method is now called in ComponentDidMount.
现在在ComponentDidMount中调用该方法。
I also binded getData() to my constructor but I still get the error above. 我也将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;
I'm also using create-react-app from Github. 我也在使用Github的create-react-app。 Please some assistance will be helpful.
请提供一些帮助。
Thanks! 谢谢!
When you reference defined methods you need to say this
so: 当你的参考定义的方法,你需要说
this
如此:
componenDidMount() {
this.getData()
.then(data => {
this.setState({
people: data
});
});
}
Try adding this.
尝试添加
this.
when calling your functions. 调用函数时。
this.getData()
inside componentDidMount
componentDidMount
this.getData()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.