为什么我这样设置ref.current也是自增的,并不是不变的
import React, { useState, useEffect, useLayoutEffect, useMemo, useCallback, useRef } from "react";
export default function StateFunction() {
const [num, setNum] = useState(1)
/*****useRef的使用 start======***********************/
const ref = useRef()
useEffect(() => {
ref.current = setInterval(() => {
setNum(value => value + 1)
}, 1000);
})
useEffect(() => {
if (num > 10) {
console.log('num>10');
clearInterval(ref.current)
}
console.log('ref =', ref);
}, [num])
/*****useRef的使用 end======***********************/
return (
<div>
这是一个函数组件:
<div>num={num}</div>
</div>
)
}
输出:
ref = {current: 2}
TestUseRef.js:22 ref = {current: 4}
TestUseRef.js:22 ref = {current: 5}
TestUseRef.js:22 ref = {current: 6}
TestUseRef.js:22 ref = {current: 7}
TestUseRef.js:22 ref = {current: 8}
TestUseRef.js:22 ref = {current: 9}
TestUseRef.js:22 ref = {current: 10}
TestUseRef.js:22 ref = {current: 11}
TestUseRef.js:22 ref = {current: 12}
TestUseRef.js:20 num>10
TestUseRef.js:22 ref = {current: 13}