简体   繁体   English

反应js从服务器获取数据并渲染

[英]react js fetching data from server and render

I'm using React js and the Biff Flux implementation. 我正在使用React js和Biff Flux实现。 I have a question on the best way of achieving load from server. 我对从服务器实现负载的最佳方法有疑问。

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
}

Is this the correct way of doing it? 这是正确的做法吗? Sometimes I have a Controller that loads the data and sends it as props to it's child components but still I don't know the best way of render the component when I must wait for a response from the server. 有时我有一个Controller来加载数据并将其作为道具发送给它的子组件,但是当我必须等待服务器的响应时,我仍然不知道呈现组件的最佳方法。

Usually you would want to have the ajax call at the top component. 通常,您可能希望在顶部组件进行ajax调用。 And you would like to send data to child components via props. 而且您想通过道具将数据发送到子组件。

While your methods looks correct. 虽然您的方法看起来正确。 You can use localStorage to cache the response for the 1st time and show it until original data is fetched from the server. 您可以使用localStorage第一次缓存响应并显示它,直到从服务器中获取原始数据为止。

This will make your app look faster. 这将使您的应用看起来更快。

Something like: 就像是:

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
}

If you are not looking at a cache solution, then your method is fine. 如果您不打算使用缓存解决方案,那么您的方法很好。 I hope this helps you. 我希望这可以帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM