React AJAX


Release date:2024-03-15 Update date:2024-03-15 Editor:admin View counts:34

Label:

React AJAX

Data from the React component can be accessed through the componentDidMount method, and when getting data from the server, it can be stored in the state , reuse this.setState method to re-renderUI.

When loading data asynchronously, use the componentWillUnmount to cancel the outstanding request.

The following example demonstrates getting the latest Github user updates gist share description:

React instance

classUserGistextendsReact.Component{constructor(props){super(props);this.state={username:'',lastGistUrl:''};}componentDidMount(){this.serverRequest=
$.get(this.props.source,function(result){varlastGist=result[0];this.setState({username:lastGist.owner.login,lastGistUrl:lastGist.html_url});}.bind(this));}componentWillUnmount(){this.serverRequest.abort();}render(){return(<div>{this.state.username}User's latest Gist shared address:
<ahref={this.state.lastGistUrl}>{this.state.lastGistUrl}</a>
</div>);}}ReactDOM.render(<UserGistsource="https://api.github.com/users/octocat/gists"/>,document.getElementById('example'));

The above code uses jQuery to complete the Ajax request.

Powered by TorCMS (https://github.com/bukun/TorCMS).