react/docs/tips/12-initial-ajax.md

54 lines
1.2 KiB
Markdown
Raw Normal View History

2013-10-07 10:10:18 +08:00
---
id: initial-ajax
title: Load Initial Data via AJAX
layout: tips
2013-10-07 10:10:18 +08:00
permalink: initial-ajax.html
prev: dom-event-listeners.html
2013-10-30 01:42:47 +08:00
next: false-in-jsx.html
2013-10-07 10:10:18 +08:00
---
2013-11-13 05:15:45 +08:00
Fetch data in `componentDidMount`. When the response arrives, store the data in state, triggering a render to update your UI.
2013-10-07 10:10:18 +08:00
When fetching data asynchronously, use `componentWillUnmount` to cancel any outstanding requests before the component is unmounted.
2013-11-23 04:32:53 +08:00
This example fetches the desired Github user's latest gist:
2013-10-07 10:10:18 +08:00
```js
var UserGist = React.createClass({
getInitialState: function() {
return {
username: '',
lastGistUrl: ''
};
},
2013-12-31 06:54:41 +08:00
2013-10-07 10:10:18 +08:00
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();
2013-10-07 10:10:18 +08:00
},
2013-12-31 06:54:41 +08:00
2013-10-07 10:10:18 +08:00
render: function() {
return (
<div>
{this.state.username}'s last gist is
<a href={this.state.lastGistUrl}>here</a>.
</div>
);
}
});
ReactDOM.render(
2013-10-30 02:20:04 +08:00
<UserGist source="https://api.github.com/users/octocat/gists" />,
mountNode
2013-10-07 10:10:18 +08:00
);
```