[英]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.