2017-12-01 6 views
0

私は反応が新しく、randomuserapiからデータを取得して表示しようとしています。私は、API呼び出しを作ったが、私は私のアプリを実行すると、私は次のエラーを取得:リアクションクラスメソッドが定義されていないno-undef

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

がここに以下の私のコードです:私は、API呼び出しを行う場所のgetData()メソッドです。このメソッドは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も使用しています。助けてくださいいくつかの助けてください。

ありがとうございます!

答えて

2

あなたがそうthisを言う必要が定義されているメソッド参照:あなたの関数を呼び出すときに

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

ありがとうございます。うまくいく – jintus95

1

this.を追加してみてくださいを。 this.getData()内側componentDidMount

関連する問題