[英]React class method not defined no-undef
我是新来的反应者,我正在尝试从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。 请提供一些帮助。
谢谢!
当你的参考定义的方法,你需要说this
如此:
componenDidMount() {
this.getData()
.then(data => {
this.setState({
people: data
});
});
}
尝试添加this.
调用函数时。 componentDidMount
this.getData()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.