在使用效果中使用Ref Vs Ref. -Current有什么区别?

发布于 2025-02-14 01:36:41 字数 246 浏览 0 评论 0原文

我有以下参考变量:

const renderRefs = useRef()

之间的差异是什么:

  useEffect(() => {
   
  }, [renderRefs.current])

两者

  useEffect(() => {
   
  }, [renderRefs])

I have the following ref variable :

const renderRefs = useRef()

What is the differenece beetween using:

  useEffect(() => {
   
  }, [renderRefs.current])

and

  useEffect(() => {
   
  }, [renderRefs])

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

遮了一弯 2025-02-21 01:36:41

假设您打算参考相同的参考 -

useref返回的REF对象是稳定的。它不会在重新订阅者之间发生变化。由于始终是相同的,所以这

useEffect(() => {

}, [refItem])

等同于

useEffect(() => {

}, [])

.current ref的属性中的任何内容都可能会在重新订阅中进行更改,具体取决于REF的使用方式。将.current属性放在依赖项数组中的意思是:“在重新渲染后,如果值自先前渲染以来已更改,请运行效果回调。”

例如,如果您有

<button
  onClick={() => {
    refItem.current = 5;
    setSomeState('abc');
  }}
  ...

单击按钮,则由于setSomestate而导致重新效率在依赖项数组中并运行效果回调。

如果ref值曾经在最后一个渲染上为5,则在上面的点击处理程序内进行refitem.current = 5表示效果呼叫将在下一个下一个 not 运行渲染,因为前5个值等于当前值5。

设置状态很重要。如果您不设置状态,则组件不会重新渲染,并且组件未重新渲染,则未检查依赖项数组值(也没有发生任何其他情况)。因此,仅执行

<button
  onClick={() => {
    refItem.current = 5;
  }}
  ...

不足以触发效果回调。

Assuming you meant to refer to the same ref -

The ref object returned by useRef is stable. It will not change across re-renders. Since it's always the same, this

useEffect(() => {

}, [refItem])

is equivalent to

useEffect(() => {

}, [])

Whatever exists in the .current property of the ref may well change across re-renders, depending on how the ref is used. Putting the .current property in the dependency array means: "After a re-render, if the value has changed since the prior render, run the effect callback."

For example, if you had

<button
  onClick={() => {
    refItem.current = 5;
    setSomeState('abc');
  }}
  ...

clicking the button would result in a re-render due to setSomeState, and then if the ref value used to be something other than 5 on the last render, React will detect a change in the dependency array and run the effect callback.

If the ref value used to be 5 on the last render, then doing refItem.current = 5 inside the click handler above means that the effect callback will not run after the next render, because the previous value of 5 is equal to the current value of 5.

Setting state is important. If you don't set state, the component won't re-render, and if the component doesn't re-render, the dependency array values aren't checked (nor does anything else occur). So, doing only

<button
  onClick={() => {
    refItem.current = 5;
  }}
  ...

is not sufficient to trigger the effect callback.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文