简体   繁体   English

反应:useState() 与 useRef()

[英]React: useState() vs useRef()

I've gone through the React Docs once.我已经浏览过一次 React Docs。

I'm trying to compare useState() with useRef() in my mind…我试图在我的脑海中比较 useState() 和 useRef() ......

Commonalities to both useState() and useRef(): useState() 和 useRef() 的共同点:

  • Available in functional components only仅在功能组件中可用
  • Create static values – value persists between function calls创建静态值——值在函数调用之间保持不变
  • Values are mutable值是可变的
  • Are scoped within their function component范围在其功能组件内
  • Scope includes other hooks (use's) within their function component范围包括其功能组件中的其他钩子(使用)

Differences between useState() and useRef(): useState() 和 useRef() 的区别:

  • useState triggers re-render, useRef does not. useState 会触发重新渲染,而 useRef 不会。
  • useRef can reference child elements (via “ref={}”), useState can't. useRef 可以引用子元素(通过“ref={}”),useState 不能。
  • For child DOM elements, ref={} refers to the DOM element itself.对于子 DOM 元素,ref={} 指的是 DOM 元素本身。
  • For child React components, ref={} refers to the child component itself.对于子 React 组件, ref={} 指的是子组件本身。

…And this previous Stackoverflow question adds: …… 之前的 Stackoverflow 问题补充说:

  • useState updates it's value asynchronously, useRef updates synchronously. useState 异步更新它的值,useRef 同步更新。

So I have 3 questions so far:所以到目前为止我有3个问题:

  1. Are the above commonalities & differences correct?以上共性和差异是否正确?
  2. Any other commonalities or differences I should be aware of?我应该注意的任何其他共性或差异?
  3. From the component that creates the reference (useRef+ref={}), can I both get & set values on the child component (yes, it may/may not be wise to do so)?从创建引用的组件 (useRef+ref={}) 中,我是否可以在子组件上获取和设置值(是的,这样做可能/可能不明智)?

Basically your comparison is correct, but as already was mentioned in comments they serve different purposes.基本上你的比较是正确的,但正如评论中已经提到的,它们有不同的用途。 You just need to know is that useRef basically is syntax sugar :你只需要知道useRef基本上是语法糖

useRef() is basically useState({current: initialValue })[0] useRef() 基本上是 useState({current: initialValue })[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM