原文链接: react hook useRef
上一篇: react hook useEffect
下一篇: react hook useMemo
可以暂停的定时器, 使用ref保存 定时器的handler
import React, { useState, useEffect, useRef } from "react";
export default () => {
const [count, setCount] = useState(0);
const ref = useRef(null);
const start = () => {
console.log("start");
if (!ref.current) {
console.log("start ref");
ref.current = getInterval();
}
};
const getInterval = () => setInterval(() => setCount((c) => c + 1), 100);
const stop = () => {
console.log("stop", ref);
if (ref.current) {
console.log("clear");
clearInterval(ref.current);
ref.current = null;
}
};
useEffect(() => {
ref.current = getInterval();
console.log("===", ref);
}, []);
return (
<div>
count: {count}
<div>
<button onClick={stop}>stop</button>
<button onClick={start}>start</button>
</div>
</div>
);
};
修改ref不会重新渲染, 页面数据不会变化, 但是 输出可以看到ref已经变了
import React, { useEffect, useRef } from "react";
export default (props) => {
const ref = useRef(0);
useEffect(() => {
setInterval(() => {
console.log(ref.current);
ref.current++;
},100);
}, []);
return <div>{ref.current}</div>;
};