【问题标题】:test is updated in UI but not updating in console why ? can anyone tell about why console is not updating?测试在 UI 中更新但在控制台中没有更新,为什么?谁能告诉为什么控制台不更新?
【发布时间】:2022-01-21 20:34:03
【问题描述】:

基本上我的问题是,为什么控制台中没有更新测试状态??

import {useEffect, useRef, useState} from "react";

const Home = () => {
    let [test, setTest] = useState(0);
    const ref = useRef(0);

    useEffect(() => {
        setInterval( () => {
            console.log(test, ref);
            ref.current += 1;
             setTest( test =>test + 1);
            console.log(test, ref);
        }, 1000)
    }, [])
    return <>
        <div>
            <h1>a : {test}</h1>
            <h1>ref : {ref.current}</h1>
        </div>
    </>
}

export default Home

enter image description here

【问题讨论】:

    标签: reactjs setinterval


    【解决方案1】:

    这是因为这段代码中的useEffect 只执行了一次。 useEffect执行时的状态值为0,函数继续记住这个值。

    在第一个日志中,useEffect 执行时的值为 0,因此显示为 0。另外,使用 setState 不会立即在同一范围内更改该值。这就是为什么第二个日志也显示 0。

    根据官方文档,通过useRef返回的对象会在整个组件的生命周期中得到维护。所以,useRef的值即使在同一个作用域内也可以代表不同的值。

    【讨论】:

      猜你喜欢
      • 2022-10-13
      • 2019-07-16
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      • 2020-07-04
      • 2020-05-17
      • 1970-01-01
      相关资源
      最近更新 更多