我在其中一個組件中獲取API,並將其數據發送到dataAPI
狀態。它工作正常。獲取API並使其數據可通過組件訪問
但我想開始將我的應用分解成更小的組件。我希望能夠從任何其他組件訪問數據。而且我不想每次都要做一個不同的API調用。
這是我下面的組件,其中的數據被拉。從應用程序中訪問API數據的最佳方式是什麼?
我現在還在使用setInterval()
來每分鐘刷新一次數據。
謝謝!
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
dataAPI: [],
isLoading: true
};
// Refresh data every 60 seconds (60,000 ms)
setInterval(() => {
this.componentDidMount();
}, 60000);
}
componentDidMount() {
this.fetchData();
}
render() {
var {isLoading} = this.state;
if(isLoading)
return this.renderLoadingMessage();
else
return this.renderResults();
}
fetchData() {
var url = 'https://www.myapi.com';
fetch(url)
.then(response => response.json())
.then(jsonData => {
var myData = [];
console.log(jsonData);
myData.push(jsonData);
this.setState({
isLoading: false,
dataAPI: [].concat(myData)
});
})
.catch(error => console.log('Fetch error ' + error));
}
renderLoadingMessage() {
return (
<View>
<ActivityIndicator animating={true} />
</View>
);
}
renderResults() {
var {isLoading} = this.state;
var d = this.state.dataAPI[0];
if (!isLoading) {
return (
<View>
<Text>
{d.artist}
</Text>
</View>
);
}
}
};
AppRegistry.registerComponent('Home',() => Home);
您需要一種模式將響應設置爲「全局,應用程序級」狀態容器。谷歌的「Redux」,「MobX」或「Flux」來理解這個概念。然後你可以從你想要的任何組件訪問內容,因爲它存儲爲一個狀態樹,並作爲觀察組件的道具傳遞。 – zvona