工程树
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);
this.reset();
},
reset() {
this.count = 0;
}
}
export default class Preant 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>
)
}
}
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'
class App extends React.Component {
render() {
return (
<HashRouter>
<Switch>
<Route exact path='/1' component={Home}></Route>
<Route path='/demo1' component={Demo1}></Route>
</Switch>
</HashRouter>
);
}
}
export default App;
如不销毁组件定时器,则在转换路由路径时,会报错,如下图
同时,在下次开启定时时,还会上一次未销毁的定时器,会连同这一次的定时器,以一秒增加两次的速度递增,如下图
import React from "react";
class Home extends React.Component {
render() {
return (
<div >
Home
</div>
);
}
}
export default Home;
|