使用 ReactJS + Redux + Cloud Endpoints 获取初始页面数据

Fetch initial page data with ReactJS + Redux + Cloud Endpoints

我使用 ReactJS + Redux + Google 云端点。现在,对于初始页面加载,我必须通过 Cloud Enpoints 获取和显示数据。那将如何实现?完整的代码示例表示赞赏!

您基本上是在空白状态下安装您的应用程序,无论是使用叠加层还是加载微调器,然后在 componentDidMount() 中获取数据。来自 the React docs.

Load Initial Data via AJAX

Fetch data in componentDidMount. When the response arrives, store the data in state, triggering a render to update your UI.

When fetching data asynchronously, use componentWillUnmount to cancel any outstanding requests before the component is unmounted.

This example fetches the desired Github user's latest gist:

var UserGist = React.createClass({
  getInitialState: function() {
    return {
      username: '',
      lastGistUrl: ''
    };
  },

  componentDidMount: function() {
    this.serverRequest = $.get(this.props.source, function (result) {
      var lastGist = result[0];
      this.setState({
        username: lastGist.owner.login,
        lastGistUrl: lastGist.html_url
      });
    }.bind(this));
  },

  componentWillUnmount: function() {
    this.serverRequest.abort();
  },

  render: function() {
    return (
      <div>
        {this.state.username}'s last gist is
        <a href={this.state.lastGistUrl}>here</a>.
      </div>
    );
  }
});

ReactDOM.render(
  <UserGist source="https://api.github.com/users/octocat/gists" />,
  mountNode
);