除了绑定 DOM, 发现直接找一个外部变量替代 useRef() 更方便呀? 比如:
例子 1:
function Timer() {
const intervalRef = useRef();
useEffect(() => {
const id = setInterval(() => {
// ...
});
intervalRef.current = id;
return () => {
clearInterval(intervalRef.current);
};
});
// ...
}
替换成:
let _interval = null;
function Timer() {
useEffect(() => {
const id = setInterval(() => {
// ...
});
_interval = id;
return () => {
clearInterval(_interval);
};
});
// ...
}
例子 2:
function usePrevious(val) {
const r = useRef();
useEffect(() => r.current = val);
return r.current;
}
替换成:
let _p = null;
function usePrevious(val) {
useEffect(() => _p = val);
return _p;
}