gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:23:58 25 4
gpt4 key购买 nike

我正在创建一个应用程序,我需要在初始渲染时创建一个对象并在整个组件生命周期内保留它。

我的代码现在看起来像这样:

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 returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

来自:https://reactjs.org/docs/hooks-reference.html#useref

看来我用的很到位。然而,Hooks FAQ 说:

You might also occasionally want to avoid re-creating the useRef() initial value. For example, maybe you want to ensure some imperative class instance only gets created once:

function Image(props) {
// ⚠️ IntersectionObserver is created on every render
const ref = useRef(new IntersectionObserver(onIntersect));
// ...
}

useRef does not accept a special function overload like useState. Instead, you can write your own function that creates and sets it lazily:


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

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

最佳答案

So does the initial value get recreated or not?

是的,可以重新创建初始值,但随后会丢弃。因此你可以在 useRef 中保留一些值并且它不会在重新渲染之间丢失,你也可以根据需要修改它。

similar对于 useState,如果您将一个值传递给它的构造函数,它会被重新计算,但随后会被丢弃。您可以将函数传递给 useState,它只会执行一次。显然根据文档,useRef 没有这样的选项。但是你可以根据 docs 来模拟:

const ref = useRef(null);

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

关于reactjs - useRef react Hook 的确切行为是什么?是否在每次重新渲染时重新创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72402329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com