App.js
import React from ‘react‘;
import Demo1 from ‘./components/Demo1/parent‘;
import Home from ‘./components/Home‘;
import { HashRouter, Route, Switch } from ‘react-router-dom‘;
function App() {
return (
<HashRouter>
<Switch>
<Route exact path="/" component={Home}></Route>
<Route path="/demo1" component={Demo1}></Route>
</Switch>
</HashRouter>
);
}
export default App;
src\components\Home.jsx
import React from ‘react‘;
function Home() {
return <div>Home</div>;
}
export default Home;
src\components\Demo1\parent.jsx
import React from ‘react‘;
/**
* 计数例子
*
* 定时器
* 网络请求
* 事件监听
* 在组件被销毁前都应该得到相应的处理
*
*/
const MyAPI = {
count: 0,
subscribe(cb) {
this.intervalId = setInterval(() => {
this.count += 1;
cb(this.count);
}, 1000);
},
unSubscribe() {
clearInterval(this.intervalId);
},
reset() {
this.count = 0;
},
};
export default class parent extends React.Component {
state = {
count: 0,
};
componentDidMount() {
MyAPI.subscribe((currentCount) => {
this.setState({
count: currentCount,
});
});
}
render() {
console.log(this.state.count);
return <div>Parent: {this.state.count}</div>;
}
}
现象:
解决方案:
在componentWillUnmount处理相应的事件
src\components\Demo1\parent.jsx
import React from ‘react‘;
/**
* 计数例子
*
* 定时器
* 网络请求
* 事件监听
* 在组件被销毁前都应该得到相应的处理
*
*/
const MyAPI = {
count: 0,
subscribe(cb) {
this.intervalId = setInterval(() => {
this.count += 1;
cb(this.count);
}, 1000);
},
unSubscribe() {
clearInterval(this.intervalId);
},
reset() {
this.count = 0;
},
};
export default class parent extends React.Component {
state = {
count: 0,
};
componentDidMount() {
MyAPI.subscribe((currentCount) => {
this.setState({
count: currentCount,
});
});
}
componentWillUnmount() {
MyAPI.unSubscribe();
}
render() {
console.log(this.state.count);
return <div>Parent: {this.state.count}</div>;
}
}
效果:
原文:https://www.cnblogs.com/lhongsen/p/14466774.html