2016-05-29 6 views
0

は完璧にうまく機能している典型的なコンテナコンポーネントです:React:ajax APIコールを別のコンポーネントに移動するにはどうすればよいですか?ここ

const API = 'https://randomuser.me/api/?results=5'; 
class App extends Component { 

    constructor(props) { 
     super(props); 
     this.state = { profiles: [] }; 
    } 

    componentDidMount() { 
     this.fetchProfiles(); 
    } 

    fetchProfiles() { 
     let url = API; 
     fetch(url) 
     .then((res) => res.json()) 
     .then((data) => { 
      let results = data.results; 
      this.setState({ 
      profiles: results 
      }); 
     }) 
     .catch((error) => console.log('Oops! . There Is A Problem', error)); 
    } 

    render() { 
     // rendering child component here 
    } 
} 

export default App; 

私が今やろうとしていますどのような別のAPIコンポーネントにfetchProfiles機能を移動しています。

だから私は私のプロジェクトでapiフォルダ内のprofiles.jsファイルを作る:

const API = 'https://randomuser.me/api/?results=5'; 

export function fetchProfiles() { 
    let url = API; 
    fetch(url) 
    .then((res) => res.json()); 
} 

をそして今、私の主なコンポーネントの輸入をし、そうのようにそれを使用しています。

import { fetchProfiles } from '../api/profiles.js'; 


const API = 'https://randomuser.me/api/?results=5'; 
class App extends Component { 

    constructor(props) { 
     super(props); 
     this.state = { profiles: [] }; 
    } 

    componentDidMount() { 
     fetchProfiles.then((data) => { 
     let results = data.results; 
      this.setState({ 
      profiles: results 
      }); 
     }); 
    } 

    // render call etc 

しかし、私が実行したときcomponentDidMountのように呼び出すと、私はこのエラーを受け取ります:Uncaught TypeError: _profiles.fetchProfiles.then is not a function。私はthenと連鎖しようとしていますが、fetch apiは約束通りにres.json()を返します。

外部機能にfetchProfilesをラッピングしてみましたが、これも新しい約束です!しかし、何も動作しません!私はここで間違って何をしていますか?このリファクタリングを手伝ってください。

const API = 'https://randomuser.me/api/?results=5'; 

export function fetchProfiles() { 
    let url = API; 
    return fetch(url) 
     .then((response) => response.json()); 
} 

そして、コンテナコンポーネントに:私はこれを固定方法はfetch(url)自体を返すようにした

+1

あなたは(URL)をフェッチ '返す必要がし​​'自体は、あなたが戻りますので、約束してから、 'then'メソッドを使うことができます。 –

答えて

4

const API = 'https://randomuser.me/api/?results=5'; 

export function fetchProfiles() { 
    let url = API; 

    // return the promise itself 
    return fetch(url).then((res) => res.json()); 
} 
0

componentDidMount() { 
     fetchProfiles() 
     .then((data) => { 
      let results = data.results; 
      this.setState({ 
      profiles: results 
      }); 
     }); 
    } 

これが機能するようになりました!!

あなたが約束を返すだろうと、あなたが thenメソッドを使用することができますので、あなたは、 fetch(url)自体を返す必要が
関連する問題