通過AJAX加載初始數據
通過AJAX加載數據是一個很普遍的場景。在React組件中如何通過AJAX請求來加載數據呢?首先,AJAX請求的源URL應該通過props傳入;其次,最好在componentDidMount函數中加載數據。加載成功,將數據存儲在state中后,通過調用setState來觸發渲染更新界面。
注意:
AJAX通常是一個異步請求,也就是說,即使componentDidMount函數調用完畢,數據也不會馬上就獲得,瀏覽器會在數據完全到達后才調用AJAX中所設定的回調函數,有時間差。因此當響應數據、更新state前,需要先通過this.isMounted() 來檢測組件的狀態是否已經mounted。
下面是利用GitHub網站提供的API接口獲取某個用戶近況信息的例子。
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 );
使用jQuery庫所提供的ajax請求$.ajax
函數數據也存在一些問題,如兼容性問題就很令人頭疼。React推薦使用fetch庫,其在API接口層面和jQuery類似,讀者可以自行搜索相關資料,熟悉 $.ajax
可以很快上手。