useRef React Hook的确切行为是什么?对象在每次重新渲染时是否被重新创建?

4
我正在创建一个应用程序,在初始渲染时需要创建一个对象,并在整个组件生命周期内保留它。
我的代码现在看起来有点像这样:
function Component() {
  const obj = useRef(new Smth());
  return (
    <div>
      <button onClick={obj.current.p}>p</button>
      <button onClick={obj.current.c}>c</button>
    </div>
  );
};

React官方文档中写道: useRef返回一个可变的ref对象,其.current属性被初始化为传递的参数(initialValue)。返回的对象将在组件的整个生命周期中保持不变。
来自: https://reactjs.org/docs/hooks-reference.html#useref 看起来我已经正确地使用了它。然而,Hooks FAQ中说:
您可能偶尔想避免重新创建useRef()的初始值。例如,也许您想确保某个命令式类实例只被创建一次:
function Image(props) {
  // ⚠️ IntersectionObserver is created on every render
  const ref = useRef(new IntersectionObserver(onIntersect));
  // ...
}

useRef不像useState那样接受特殊的函数重载。相反,你可以编写自己的函数来懒加载创建和设置它:


function Image(props) {
  const ref = useRef(null);

  // ✅ IntersectionObserver is created lazily once
  function getObserver() {
    if (ref.current === null) {
      ref.current = new IntersectionObserver(onIntersect);
    }
    return ref.current;
  }

  // When you need it, call getObserver()
  // ...
}

来源:https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables

那么初始值是否会被重新创建?

1个回答

5

那么初始值是否会被重新创建呢?

是的,初始值可以被重新创建,但随后它会被忽略
例如,在这里:

function Table(props) {
  // ⚠️ someFunc() is called on every render
  // But after first (or maybe second render if it is strict mode) it's value is ignored
  const rows = useRef(someFunc(props.count));
  // ...
}

如果你将一个值传递给它的构造函数,它会重新计算,但然后被丢弃,这与useState类似。你可以向useState传递一个函数,该函数只会执行一次。根据文档显示,useRef没有这样的选项。但是你可以通过模拟来实现。

const ref = useRef(null);

// ✅ IntersectionObserver is created lazily once
function getObserver() {
  if (ref.current === null) {
    ref.current = new IntersectionObserver(onIntersect);
  }
  return ref.current;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接