通過AJAX加載數據是一個很普遍的場景。在React組件中如何通過AJAX請求來加載數據呢?首先,AJAX請求的源URL應該通過props傳入;其次,最好在componentDidMount函數中加載數據。加載成功,將數據存儲在state中后,通過調用setState來觸發渲染更新界面。
AJAX通常是一個異步請求,也就是說,即使componentDidMount函數調用完畢,數據也不會馬上就獲得,瀏覽器會在數據完全到達后才調用AJAX中所設定的回調函數,有時間差。因此可以使用 componentWillUnmount 來取消任何未完成的請求;
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(); }
官網是這么解釋的
When fetching data asynchronously, use componentWillUnmount
to cancel any outstanding requests before the component is unmounted.
當異步加載數據的時候, 使用 componentWillUnmount 來取消任何未完成的請求 在組件卸載之前
componentWillUnmount()
在組件從 DOM 中移除的時候立刻被調用。
在該方法中執行任何必要的清理,比如無效的定時器,或者清除在 componentDidMount
中創建的 DOM 元素