React 組件的數(shù)據(jù)可以通過 componentDidMount 方法中的 Ajax 來獲取,當(dāng)從服務(wù)端獲取數(shù)據(jù)庫可以將數(shù)據(jù)存儲(chǔ)在 state 中,再用 this.setState 方法重新渲染 UI。
當(dāng)使用異步加載數(shù)據(jù)時(shí),在組件卸載前使用 componentWillUnmount 來取消未完成的請求。
以下實(shí)例演示了獲取 Github 用戶最新 gist 共享描述:
class UserGist extends React.Component {
constructor(props) {
super(props);
this.state = {username: '', lastGistUrl: ''};
}
componentDidMount() {
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() {
this.serverRequest.abort();
}
render() {
return (
<div>
{this.state.username} 用戶最新的 Gist 共享地址:
<a href={this.state.lastGistUrl}>{this.state.lastGistUrl}</a>
</div>
);
}
}
ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
document.getElementById('example')
);
以上代碼使用 jQuery 完成 Ajax 請求。
更多建議: