在react开发过程中,有时我们会遇到内存泄漏的问题,例如
常见的错误:
这种错误就说明了,我们的内存发生了泄漏,就是当我们在componentDidMount里面发送异步请求是,返回的数据还没有来得及进行渲染的时候,我们的组件就已经销毁了,不能进行this.setState。
那么,我们如何进行解决呢?
1.在componentWillUnmount里面进行处理异步函数(网上的结果,本人没有试过)
componentWillUnmount = () => {
this.setState = (state,callback)=>{
return;
};
}
这样可以解决,缺点就是,每次当组件销毁的时候,都要进行处理
2.封装一个方法,使用es6的修饰器,统一对组件类进行处理。
function inject_component_will_unmount (target) {
let next = target.prototype.componentWillUnmount
target.prototype.componentWillUnmount = function(){
if(next) next.call(this,...arguments)
this.unmount = true
}
let setState = target.prototype.setState
target.prototype.setState = function () {
if(this.unmount) return
setState.call(this,...arguments)
}
}
然后再组件类前面进行修饰
@inject_component_will_unmount
class MyPage extends Component{
}
3.在组件销毁前,要保证清除定时器
注意:
1).对package.json进行修改,添加一下内容
"babel": {
"plugins": [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
]
],
"presets": [
"react-app"
]
}
2).把vscode设置里面 experimentalDecorators进行修改,调成true