问答详情
源自:3-6 长久保存数据——useRef

为什么我这样设置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}


提问者:夏目沫沫 2022-04-11 10:28

个回答

  • 慕函数8463949
    2022-05-01 15:41:47

    后面依赖项数组如果不写,就相当于添加了所有的依赖项,依赖项为[],则表示不依赖任何属性,这样useEffect就相当于只执行一次,ref.current是不变的,只有一个值,因为只执行了一次,否则相当于多次执行useEffect,每次重新执行setInterval 都会有一个新id