在 componentDidMount
時(shí)加載數(shù)據(jù)。當(dāng)加載成功,將數(shù)據(jù)存儲(chǔ)在 state 中,觸發(fā) render 來(lái)更新你的 UI。
當(dāng)執(zhí)行同步請(qǐng)求的響應(yīng)時(shí),在更新 state 前, 一定要先通過(guò) this.isMounted()
來(lái)檢測(cè)組件的狀態(tài)是否還是 mounted。
下面這個(gè)例子請(qǐng)求了一個(gè) Github 用戶最近的 gist:
var UserGist = React.createClass({
getInitialState: function() {
return {
username: '',
lastGistUrl: ''
};
},
componentDidMount: function() {
$.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: function() {
return (
<div>
{this.state.username}'s last gist is
<a href={this.state.lastGistUrl}>here</a>.
</div>
);
}
});
React.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
mountNode
);