Can't perform a React state update on an unmounted component. This is a no-op...... 复制代码
程序的运行须要内存。只要程序提出要求,操做系统或者运行时(runtime)就必须供给内存。javascript
对于持续运行的服务进程(daemon),必须及时释放再也不用到的内存。不然,内存占用愈来愈高,轻则影响系统性能,重则致使进程崩溃。html
再也不用到的内存,没有及时释放,就叫作内存泄漏(memory leak)。java
function leaks(){
leak = '***'; //leak 成为一个全局变量,不会被回收
}
复制代码
var leaks = (function(){
var leak = '***';// 被闭包所引用,不会被回收
return function(){
console.log(leak);
}
})()
复制代码
document.querySelector("#demo").addEventListener('click', myFunction);
var para1=document.querySelector("#demo");
para1.parentNode.removeChild(para1);
复制代码
若是咱们在没有取消 click 方法前去销毁了 para1 节点,就会形成内存泄露。react
正确的作法:promise
document.querySelector("#demo").addEventListener('click', myFunction);
// 咱们须要在删除节点前清除挂载的 click 方法
document.querySelector("#demo").removeEventListener("click", myFunction);
var para1=document.querySelector("p1");
para1.parentNode.removeChild(para1);
复制代码
componentWillMount: function () {
var onLogin = this.props.onLogin || function () {},
onLogout = this.props.onLogout || function () {};
this.on('authChange', function () {
console.log('user authenticated:', this.state.isAuthenticated);
return this.state.isAuthenticated
? onLogin(this.state)
: onLogout(this.state);
}.bind(this));
},
复制代码
componentWillMount
的时候挂载了authChange
事件,而后 react 出现了以下的报错:componentWillUnmount: function () {
this.off('authChange', this.authChange);
this.authChange = null;
}
复制代码
很明显这种状况就是在 dom 结构销毁的时候,事件却没有清除致使的内存泄漏,因此咱们须要在
componentWillUnmount
的时候去清除挂载的方法bash
这里就提到了内存泄露,当咱们在使用事件绑定,setInterval,setTimeOut 或一些函数的时候,可是却没有在组件销毁前清除的时候会形成内存泄露。这里咱们手动的再componentWillUnmount
去清除相关的方法便可。闭包
why:app
this.pwdErrorTimer = setTimeout(() => {
this.setState({
showPwdError:false
})
}, 1000);
复制代码
设置了一个timer延迟设置state,然而在延迟的这段时间,组件已经销毁,则形成此类问题async
componentWillUnmount(){
clearTimeout(this.pwdErrorTimer);
clearTimeout(this.userNameErrorTimer);
}
复制代码
文档中提到了两个重要的概念
为何要在 effect 中返回一个函数?
React 什么时候清除 effect?
提示
若是你熟悉 React class 的生命周期函数,你能够把 useEffect Hook 看作 componentDidMount,componentDidUpdate 和 componentWillUnmount 这三个函数的组合。