useRef() 而不是仅仅声明一个变量有什么优点? [英] What are the advantages of useRef() instead of just declaring a variable?

查看:77
本文介绍了useRef() 而不是仅仅声明一个变量有什么优点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Looking at the hooks docs and some blogs we understand that when using useRef() we have a mutable value stored.

文档:

您可能熟悉 refs,主要是作为访问 DOM 的一种方式.如果您将 ref 对象传递给 React with ,React 会在该节点发生更改时将其 .current 属性设置为相应的 DOM 节点.

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.

然而,useRef() 不仅仅用于 ref 属性.将任何可变值保持在类似于在类中使用实例字段的方式非常方便.

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.

这是可行的,因为 useRef() 创建了一个普通的 JavaScript 对象.useRef() 和自己创建一个 {current: ...} 对象之间的唯一区别是 useRef 将在每次渲染时为您提供相同的 ref 对象.

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 声明和使用变量相比,这给我们带来了哪些优势?

What advantages does this give us over just declaring and using a variable with let?

代码示例:

import React, {useRef} from "react";
const MyFunctionalComponent = (props) => {
    const refVariable = useRef('value');
    //versus
    let letVariable = 'value';
}

跟进:给出的答案很有帮助,并结合一些测试给了我所需的理解.如果有人遇到这个概念有问题,我现在理解的方式是:

Follow up: The answers given were helpful, and combined with some testing gave me the understanding I needed. If anyone comes across this having trouble with the concept, the way I understand it now is:

  • 您可以拥有实例变量,但它们确实是即时的,每次重新渲染都会重新初始化它们.
  • useRef() 给你一些更持久的东西,比如 useState() 但更新不会触发重新渲染,如果你以链接方式进行大量操作,但不想触发重新渲染,这非常有用-渲染到最后
  • useState() 应该只与 UI 元素使用的变量相关联,因为对状态的任何更改都会触发整个组件的重新渲染.在整个过程中不要有一连串操作状态的操作,使用 refs 直到链的末端.

推荐答案

我正在更改我的答案并将人们推荐给下面的 Arman,因为它更贴切.本质上,对于功能组件,整个 函数在每次重新渲染时都会运行.这意味着在函数体中使用简单的 let x = 5; 初始化的变量将在每次渲染时重新初始化,重置它们.这就是我们需要像 useRef 这样的钩子的原因,它给一个 reference 一个在渲染之间持续存在的值

I'm changing my answer and referring people to Arman's below, since it's the more apt one. In essence, for functional components the entire function gets run every time it re-renders. Which means variables that are initialized with a simple let x = 5; in the body of the function will get re-initialized every render, resetting them. That's the reason we need hooks like useRef, it gives a reference to a value that persists between renders

这篇关于useRef() 而不是仅仅声明一个变量有什么优点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆