Ajax in the React
The data source of the component, usually obtained from the server via an AJAX request, can be used to componentDidMount
set the AJAX request, wait until the request succeeds, and then use the this.setState
method to re-render the UI.
var UserGist = React.createClass({ getInitialState(){ return { username:‘‘, lastGistUrl:‘‘ }; }, componentDidMount(){ $.get(this.props.source,function(result){ var lastGist = result[0]; if(this.isMounted()){ this.SetState({ userName:lastGist.owner.login, lastGistUrl:lastGist.html_url }) } }.bind(this)); }, render(){ 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" />, document.body)
The above code uses jquery to complete the AJAX request, which is for illustrative purposes. React itself has no dependencies, and can use other libraries without jquery.
We can even pass a promise object into the component.
ReactDOM.render( <RepoList promise={$.getJSON(‘https://api.github.com/search/repositories?q=javascript&sort=stars‘)} />, document.body)
The above code fetches the data from the GitHub API and then passes the Promise object as a property to the RepoList
component.
If the Promise object is fetching data (pending state), the component displays "Loading", if the Promise object is error (rejected status), the component displays an error message, and if the Promise object fetches the data successfully (fulfilled state), The component displays the obtained data.
var repolist = React.createclass ({getinitialstate:function () {return {loading:true, error:null, data:null}; }, Componentdidmount () {This.props.promise.then (value = = This.setstate ({loading:false, data:value}), Error = This.setstate ({loading:false, error:error})); }, Render:function () {if (this.state.loading) {return <span>Loading...</span>; } else if (This.state.error!== null) {return <span>error: {this.state.error.message}</span>; } else {var repos = This.state.data.items; var repolist = Repos.map (function (repo) {return (<li> <a href={repo.html_url}>{r Epo.name}</a> ({Repo.stargazers_count} stars) <br/> {repo.description} </li>); }); Return (<main>
Ajax in React