[英]data scope in React using Fetch
我試圖了解如何使用fetch從API獲取數據並使用它來創建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'))
如果您能向我指出任何可以幫助我理解這一概念的資源,我將不勝感激。 先感謝您。
在示例代碼中,您沒有返回“ resp.json()”,resp.json()將返回一個promise,您需要返回該promise,如果解析成功,則在下一個.then( )將使用API響應中的對象填充。 然后,您可能希望將響應數據設置為組件狀態以執行某些操作。
我用'create-react-app'創建了一個簡單的react應用程序來演示這一點:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.