【发布时间】:2019-10-20 16:37:12
【问题描述】:
我正在“Hooks FAQ”阅读有关 React useState() 和 useRef() 的信息,我对一些似乎同时具有 useRef 和 useState 解决方案的用例感到困惑,但我不是确定哪种方式是正确的。
来自“Hooks 常见问题解答”about useRef():
“useRef() Hook 不仅仅用于 DOM refs。“ref”对象是一个通用容器,其当前属性是可变的并且可以保存任何值,类似于类上的实例属性。”
使用 useRef():
function Timer() {
const intervalRef = useRef();
useEffect(() => {
const id = setInterval(() => {
// ...
});
intervalRef.current = id;
return () => {
clearInterval(intervalRef.current);
};
});
// ...
}
使用 useState():
function Timer() {
const [intervalId, setIntervalId] = useState(null);
useEffect(() => {
const id = setInterval(() => {
// ...
});
setIntervalId(id);
return () => {
clearInterval(intervalId);
};
});
// ...
}
两个示例的结果相同,但哪个更好 - 为什么?
【问题讨论】:
标签: reactjs react-hooks