简体   繁体   English

在 useCallback 挂钩中获取 ref null

[英]Getting ref null inside useCallback hook

I'm trying to set the value of input using ref but I'm getting ref null inside useCallback Hook.我正在尝试使用 ref 设置输入的值,但我在 useCallback Hook 中得到了 ref null。

let inputRef = useRef();
const search = useCallback(
        (data) => {
            console.log(inputRef);
        },
        [inputRef],
    );

return <input type="text" ref={inputRef} />

and It's showing null in the browser console when I call this function.当我调用此 function 时,它在浏览器控制台中显示null

this is just an example showing, what I'm trying to achieve.这只是一个例子,展示了我想要实现的目标。

The problem isn't that he's not passing in a null value, a ref is initialized to null by default.问题不在于他没有传入 null 值,默认情况下将 ref 初始化为null

The problem is that useCallback() memoizes and caches the result of this callback function before the first render, before the component to which this ref is assigned has been mounted.问题是useCallback()在第一次渲染之前,在这个 ref 被分配到的组件被挂载之前,记忆并缓存了这个回调 function 的结果。 It then waits for inputRef to change but inputRef is just a reference to an object;然后它等待inputRef更改,但inputRef只是对 object 的引用; even if the component that inputRef.current points to changes, the value of inputRef does not as it is only being compared by reference equality.即使inputRef.current指向的组件发生变化, inputRef的值也不会改变,因为它只是通过引用相等性进行比较。

So, since the function has no reason to update as the value of inputRef is not going to change -- it evaluates to the cached result of the search callback which was computed and cached before the DOM mounted and it outputs null to console.因此,由于 function 没有理由更新,因为inputRef的值不会改变 - 它评估search回调的缓存结果,该结果在 DOM 安装之前计算和缓存,并将null输出到控制台。

What you're looking for is a Callback Ref您正在寻找的是回调参考

在此处输入图像描述

The other thing that I'd like to point out is that the useCallback hook is not necessary for this use-case and will provide no benefit.我想指出的另一件事是 useCallback 钩子对于这个用例来说不是必需的,并且不会提供任何好处。 The only correct usage of useCallback() is to cache the result of expensive function calls so that they don't recompute every time render is called (this is known as memoization). useCallback()唯一正确的用法是缓存昂贵的 function 调用的结果,这样它们就不会在每次调用 render 时都重新计算(这称为 memoization)。

The arbitrary usage of the useCallback() hook is an anti-pattern-- it is not required for the overwhelming majority of callbacks in React, and can reduce performance when used incorrectly by creating additional overhead. useCallback() 钩子的任意使用是一种反模式——React 中绝大多数回调都不需要它,并且在使用不正确时会通过产生额外的开销而降低性能。

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

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