時間:2016-08-15 17:38:54
作者:zhongxia
地址:
React 異步解決方案
1. React官方提供的解決方案 Load Initial Data via AJAX
使用jQuery的Ajax方法,在一個組件的 componentDidMount()
中發ajax請求,拿到的數據存在組件自己的state中,并調用setState
方法去更新UI。如果是異步獲取數據,則在 componentWillUnmount
中取消發送請求。
如果只是為了使用jQuery的Ajax方法就引入整個jQuery庫,既是一種浪費又加大了整個應用的體積。那我們還有什么其他的選擇嗎?事實上是有很多的:fetch()、fetch polyfill、axios...其中最需要我們關注的是window.fetch()
,它是一個簡潔、標準化的javascript的Ajax API。在Chrome和Firefox中已經可以使用,如果需要兼容其他瀏覽器,可以使用fetch polyfill。
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}'s last gist is
<a href={this.state.lastGistUrl}>here</a>.
</div>
);
}
});
ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
mountNode
);
2. 項目如何組織Ajax請求
React官方文檔,告訴我們單個組件如何獲取數據,但是沒有告訴我們項目中,如何組織Ajax的請求,并且把數據保存在哪里?如果這部分沒有規范,多個協作開發的話,會讓項目混亂,難以維護。