简体   繁体   中英

React - Load Initial List via AJAX

I'm starting to learn react. There's an excellent example in the official docs about loading data initially via AJAX:

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
);

The code above gets the latest gist of a specific user from GitHub.

What is the best way in React to go about outputting a list of the last 10 gists of the specific user?

How would you modify the code sample above?

var UserGist = React.createClass({
    getInitialState: function() {
        return {
            gists: []
        };
    },

    componentDidMount: function() {
        this.serverRequest = $.get(this.props.source, function (result) {
            this.setState({
                gists: result
            });
       }.bind(this));
    },

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

    render: function() {
        return <div>
            {this.state.gists.map(function(gist){
                return <div key={gist.id}>{gist.owner.login}</div>
            })}
        <div>;
    }
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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