React AJAX


The data of the React component can be obtained through Ajax in the componentDidMount method. When the database is obtained from the server, the data can be stored in the state, and then the UI can be re-rendered using the this.setState method.

When using asynchronous loading of data, use componentWillUnmount to cancel outstanding requests before the component is unloaded.

The following example demonstrates obtaining the latest gist sharing description of a Github user:

Example

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>php中文网 React 实例</title>
    <script src="http://static.php.cn/assets/react/react-0.14.7/build/react.js"></script>
    <script src="http://static.php.cn/assets/react/react-0.14.7/build/react-dom.js"></script>
    <script src="http://static.php.cn/assets/react/browser.min.js"></script>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
  </head>
 <body>
    <div id="example"></div>
    <script type="text/babel">
      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" />,
        document.getElementById('example')
      );
    </script>
  </body>
</html>

Running Example»

Click the "Run Example" button to view the online example

The above code uses jQuery to complete the Ajax request.