在寫react組件的時候,會有這個警告
Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method”
解決方法:利用生命周期鈎子函數:componentWillUnmount,在組件卸載前清除timer
// 組件加載完畢 啟動定時器
settimem: setTimeout(this.iTimer, 3000),
// 定時器
iTimer = () => {
this.setState({
timer: setInterval(() => {
this.postuseinfo(sessionStorage.getItem("huihuaid"));
}, 20000),
});
// 組件清除時清除定時器
componentWillUnmount() {
clearInterval(this.state.timer && this.state.timer);
clearInterval(this.state.settimem && this.state.settimem);
}
