gpt4 book ai didi

reactjs - useRef() 而不是仅仅声明一个变量有什么优点?

转载 作者:行者123 更新时间:2023-12-03 23:27:39 26 4
gpt4 key购买 nike

查看 hooks 文档和一些博客我们了解到,在使用 useRef() 时,我们存储了一个可变值。
Docs :

You might be familiar with refs primarily as a way to access the DOM. If you pass a ref object to React with , React will set its .current property to the corresponding DOM node whenever that node changes.

However, useRef() is useful for more than the ref attribute. It’s handy for keeping any mutable value around similar to how you’d use instance fields in classes.

This works because useRef() creates a plain JavaScript object. The only difference between useRef() and creating a {current: ...} object yourself is that useRef will give you the same ref object on every render.


与仅通过 let 声明和使用变量相比,这给我们带来了哪些优势? ?
代码示例:
import React, {useRef} from "react";
const MyFunctionalComponent = (props) => {
const refVariable = useRef('value');
//versus
let letVariable = 'value';
}
跟进:
给出的答案很有帮助,并结合一些测试给了我所需的理解。如果有人遇到这个概念有问题,我现在理解的方式是:
  • 您可以拥有实例变量,但它们确实是即时的,并且每次重新渲染都会重新初始化它们。
  • useRef() 给你一些更持久的东西,比如 useState() 但更新不会触发重新渲染,如果你以链接方式进行大量操作,非常有用,但不想触发重新渲染,直到结束
  • useState() 应该只与 UI 元素使用的变量相关联,因为对状态的任何更改都会触发整个组件的重新渲染。在整个过程中不要有一连串操作状态的 Action ,使用 refs 直到链条的末端。
  • 最佳答案

    最后一句话描述得很清楚:

    useRef will give you the same ref object on every render.



    如果您自己声明一个简单的 javascript 变量,它将在每次渲染时更新。当您需要在重新渲染期间保留某些值时使用 Refs(除了使用 ref 属性进行 DOM 节点引用)

    关于reactjs - useRef() 而不是仅仅声明一个变量有什么优点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60554573/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com