[英]How to fetching data from react.js before render compontents and Cannot read property 'includes' of undefined?
[英]react js fetching data from server and render
我正在使用React js和Biff Flux實現。 我對從服務器實現負載的最佳方法有疑問。
getInitialState: function(){
return{
loading: true
};
},
componentDidMount: function(){
MyAction.fetchsomeData();
},
storeDidChange: function(){
var data = MyStore.getsomeData();
// set state
this.setState({loading: false});
},
render: function(){
// wait for render until response from server
// really?
if( this.state.loading ){
return null;
}
// do render
}
這是正確的做法嗎? 有時我有一個Controller來加載數據並將其作為道具發送給它的子組件,但是當我必須等待服務器的響應時,我仍然不知道呈現組件的最佳方法。
通常,您可能希望在頂部組件進行ajax調用。 而且您想通過道具將數據發送到子組件。
雖然您的方法看起來正確。 您可以使用localStorage第一次緩存響應並顯示它,直到從服務器中獲取原始數據為止。
這將使您的應用看起來更快。
就像是:
getInitialState: function(){
// try to return stale state from cache
// if not available, set loading to true
},
componentDidMount: function(){
MyAction.fetchsomeData();
},
storeDidChange: function(){
var data = MyStore.getsomeData();
// set state and set local storage cache
this.setState({loading: false});
},
render: function(){
// wait only if local storage does not have cached stale state
if( this.state.loading ){
return null;
}
// do render
}
如果您不打算使用緩存解決方案,那么您的方法很好。 我希望這可以幫助你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.