2017-07-13 9 views
0

フェッチを使用してAPIからデータを取得し、それを使用してReactコンポーネントを作成する方法を理解しようとしています。私はこれがデータを検索、保存、使用する正しい方法であるかどうか、あるいは私が気づいていない別の方法がある場合は混乱します(私は州とマウントに関するドキュメントで何かを読んでいますが、その周り。フェッチを使用したReactのデータスコープ

JS

//Data 
const url = 'https://api.tfl.gov.uk/BikePoint'; // API 

fetch(url) 
.then((resp) => resp.json()) // Transform the data into json 
.then(function(data) { 
    // How can I make data accessible outside this function? 
}) 

.catch(function(error) { 
    console.log(JSON.stringify(error)); 
}); 

//React 
const List = ({items, each}) => 

    <div className = "panel panel-default"> 
    <div className = "panel-heading"><h2>Bike points</h2></div> 
    <div className = "panel-body"> 

     <ul className = "list-group">{items.map((item, key) => 
     <ListItem key = {key} item = {each(item)} number={item.commonName}/>)}</ul> 

    </div> 
    </div> 

const ListItem = ({item, arrival, number}) => 
    <li className = "list-group-item">{number}</li> 

//How can access the data here? 
ReactDOM.render(<List items={data} each={ListItem} />, document.querySelector('#main')) 

CodePen

あなたは私がこの概念を理解するのに役立ちます任意のリソースに私を指摘することができれば私は幸いです。事前にありがとうございます。

答えて

1

であなたのサンプルコード、あなたはretuしていない'resp.json()'を呼び出すと、resp.json()は約束を返します。これを返す必要があり、それが正常に解決された場合、次の.then()の 'data'にはAPIレスポンス次に、コンポーネント状態の応答データを設定して、何かを実行することができます。ここ

import React, { Component } from 'react'; //import 'React' default export, and { Component } non-default export from react 
import fetch from 'isomorphic-fetch'; // isomorphic-fetch is used for both server side and client side 'fetch' (see https://github.com/matthew-andrews/isomorphic-fetch) 
// App.css was a hangover from the create-react-app, it's not really needed for this basic example 
const url = 'https://api.tfl.gov.uk/BikePoint'; // API 




class App extends Component { // This is the same as 'extends 'React.Component' 

    constructor(props) { 
     super(props); 
     this.state = { 
      fetchedData: null // stores the result of the fetch response body converted to a javascript object 
     }; 
    } 

    fetchIt =() => { 
     console.log('fetching it'); 
     fetch(url, { mode: 'cors' }) // Make sure fetch is cross-origin, it's not by default (see https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS) since the target URL of the API is a different 'origin' to our react app 
      .then((resp) => { 
      console.log(resp); 
      return resp.json(); }) 
      .then((data) => { // data input parameter is the result of the resolved resp.json() Promise (see https://developer.mozilla.org/en-US/docs/Web/API/Body/json) 
       console.log(data); 
       this.setState({ fetchedData: data }); // setState sets the component state with the data from the API response 
      }) 
      .catch(function(error) { 
       console.log(JSON.stringify(error)); 
      }); 
    } 



    render() { 
     if(!this.state.fetchedData){ // only do the fetch if there is no fetchedData already (BTW this will run many times if the API is unavailable, or 'fetchIt() encounters an error) 
      this.fetchIt(); 
     } 

    return (
     <div> 
      { 
       this.state.fetchedData ? `fetched ${this.state.fetchedData.length} entries` : 'no data' // This is a 'ternary' expression, a simple 'if->else' 
       /* equivalent to: 

       if(this.state.fetchedData) { 
        return `fetched ${this.state.fetchedData.length} entries`; // this is 'javascript string interpolation' 
       } else { 
        return 'no data'; 
       } 
       * 
       * */ 
      } 
     </div> 
    ); 
    } 
} 

export default App; // Export our component to be used by other react higher order components (parents), in this case, it's imported in 'index.js', data is only fetched when the component renders. 

の作業GitHubのレポ:

私はシンプルを作成しましたが、この証明するために「を作成反応するアプリ」でアプリを反応https://github.com/finbarrobrien/fetchy/blob/master/src/App.js

+0

フィンバーを、あなたが勝者です。私はプロジェクトをダウンロードしており、すぐに質問を投稿します。前もって感謝します。 –

+0

こんにちはFinbarr、あなたが何をしたのか理解できますか?私はコードのいくつかの部分について少し不明です。コメントは次のとおりです。[Gist code](https://gist.github.com/didacus/c674046632f05cf79500de4df9584b7d) –

+0

コメントに応じて、私のgithubリポジトリのApp.jsに新しいコミットを追加しました。うまくいけば、クロスオリジンリソース共有(CORS)、約束とjavascriptのインポート、文字列補間、三項式などを理解/学ぶための興味深い概念があります。私の言うことの一つは、自分のコードがまったく堅牢ではないということです。通常、同じAPIレスポンスデータを使用する必要がある複数のコンポーネントがあるとしたら、反応コンポーネントでそのようなフェッチを行うことはありません。すべてのフェッチを処理するfetcherモジュールと、コンポーネントに状態を渡すために使用するflux/redux –

関連する問題