我在componentDidMount中获取数据并更新状态,并出现着名的警告:
警告:无法在卸载的组件上调用setState(或forceUpdate).这是一个无操作,但它表示应用程序中存在内存泄漏.要修复,请取消componentWillUnmount方法中的所有订阅和异步任务.
我的代码如下:
componentDidMount() {
let self = this;
let apiBaseUrl = Config.serverUrl;
axios.get( apiBaseUrl + '/dataToBeFetched/' )
.then( function(response) {
self.setState( { data: response.data } );;
} );
}
Run Code Online (Sandbox Code Playgroud)
导致此警告的原因是什么是获取数据和更新状态的最佳方法?
基于之前的答案,我做了以下工作:
constructor(props) {
this.state = {isMounted: false}
}
componentDidMount() {
let apiBaseUrl = Config.serverUrl;
this.setState( { isMounted: true }, () => {
axios.get( apiBaseUrl + '/dataToBeFetched/' )
.then( (response) => { // using arrow function ES6
if( this.state.isMounted ) {
this.setState( { pets: response.data } );
}
} ).catch( error => {
// handle error
} )
} );
}
componentWillUnmount() {
this.setState( { isMounted: false } )
}
Run Code Online (Sandbox Code Playgroud)
另一个更好的解决方案是在卸载中取消请求,如下所示:
constructor(props) {
this._source = axios.CancelToken.source();
}
componentDidMount() {
let apiBaseUrl = Config.serverUrl;
axios.get( apiBaseUrl + '/dataToBeFetched/', { cancelToken: this._source.token } )
.then( (response) => { // using arrow function ES6
if( this.state.isMounted ) {
this.setState( { pets: response.data } );
}
} ).catch( error => {
// handle error
} );
}
componentWillUnmount() {
this._source.cancel( 'Operation canceled due component being unmounted.' )
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6938 次 |
| 最近记录: |