1.原先是用class组件实现轮询,大概下面的样子
class App extends Component {
constructor(props) {
super(props);
this.state = {};
this.sh = null;
}
loadDataFromServer = () => {
...
}
componentDidMount = () => {
this.sh = setInterval(this.loadDataFromServer, 3000)
}
componentWillUnmount = () => {
if(this.sh) clearInterval(this.sh)
}
render() {
return (
<div />
);
}
}
2.使用hook以后,尝试把setInterval()放在useEffect()里面,不起作用。百度了一下,有了下面的写法。
function useInterval(callback, delay) {
const savedCallback = useRef();
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}
const App = () => {
const loadDataFromServer = () => {...}
useInterval(() => {
loadDataFromServer();
}, 3000);
return (
<div />
);
}
3.为啥会有这么麻烦的东西,有没有简单的实现?还是这种的还是使用class比较好?