React 組件的數據可以通過 componentDidMount 方法中的 Ajax 來獲取,當從服務端獲取數據庫可以將數據存儲在 state 中,再用 this.setState 方法重新渲染 UI。
當使用異步加載數據時,在組件卸載前使用 componentWillUnmount 來取消未完成的請求。
以下實例演示了獲取 Github 用戶最新 gist 共享描述:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>菜鳥教程 React 實例</title>
<script src="http://static.runoob.com/assets/react/react-0.14.7/build/react.js"></script>
<script src="http://static.runoob.com/assets/react/react-0.14.7/build/react-dom.js"></script>
<script src="http://static.runoob.com/assets/react/browser.min.js"></script>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
var UserGist = React.createClass({
getInitialState: function() {
return {
username: '',
lastGistUrl: ''
};
},
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();
},
render: function() {
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')
);
</script>
</body>
</html>
