React AJAX

The data for the React component can be obtained through Ajax in the componentDidMount method, and when the database is obtained from the service side, the data can be stored in state and the UI is re-rendered using the this.setState method.

When data is loaded asynchronously, componentWillUnmount is used to cancel outstanding requests before the component is unloaded.

The following example demonstrates getting the latest gist sharing description for Github users:

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} 用户最新的 Gist 共享地址:
        <a href={this.state.lastGistUrl}>{this.state.lastGistUrl}</a>
      </div>
    );
  }
});

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

Try it out . . .

The above code uses jQuery to complete the Ajax request.

Related tutorials

AJAX tutorial