時(shí)間:2016-08-15 17:38:54
作者:zhongxia
地址:
React 異步解決方案
1. React官方提供的解決方案 Load Initial Data via AJAX
使用jQuery的Ajax方法,在一個(gè)組件的 componentDidMount()
中發(fā)ajax請(qǐng)求,拿到的數(shù)據(jù)存在組件自己的state中,并調(diào)用setState
方法去更新UI。如果是異步獲取數(shù)據(jù),則在 componentWillUnmount
中取消發(fā)送請(qǐng)求。
如果只是為了使用jQuery的Ajax方法就引入整個(gè)jQuery庫(kù),既是一種浪費(fèi)又加大了整個(gè)應(yīng)用的體積。那我們還有什么其他的選擇嗎?事實(shí)上是有很多的:fetch()、fetch polyfill、axios...其中最需要我們關(guān)注的是window.fetch()
,它是一個(gè)簡(jiǎn)潔、標(biāo)準(zhǔn)化的javascript的Ajax API。在Chrome和Firefox中已經(jīng)可以使用,如果需要兼容其他瀏覽器,可以使用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. 項(xiàng)目如何組織Ajax請(qǐng)求
React官方文檔,告訴我們單個(gè)組件如何獲取數(shù)據(jù),但是沒有告訴我們項(xiàng)目中,如何組織Ajax的請(qǐng)求,并且把數(shù)據(jù)保存在哪里?如果這部分沒有規(guī)范,多個(gè)協(xié)作開發(fā)的話,會(huì)讓項(xiàng)目混亂,難以維護(hù)。