经过AJAX加载数据是一个很广泛的场景。在React组件中如何经过AJAX请求来加载数据呢?首先,AJAX请求的源URL应该经过props传入;其次,最好在componentDidMount函数中加载数据。加载成功,将数据存储在state中后,经过调用setState来触发渲染更新界面。html
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.async
当异步加载数据的时候, 使用 componentWillUnmount 来取消任何未完成的请求 在组件卸载以前函数
componentWillUnmount()fetch
在组件从 DOM 中移除的时候马上被调用。this
在该方法中执行任何须要的清理,好比无效的定时器,或者清除在 componentDidMount
中建立的 DOM 元素url