[英]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.