gpt4 book ai didi

reactjs - 使用 useState "setter"函数作为回调引用是否安全?

转载 作者:行者123 更新时间:2023-12-03 15:52:21 24 4
gpt4 key购买 nike

使用 useState 的 setter 函数是否安全?钩子(Hook)作为回调引用函数?这会对 Suspense 或其他即将到来的 React 更改造成麻烦吗?如果“是的,这没关系”,那就太酷了!如果“不”为什么不呢?如果“也许”,那么什么时候可以,什么时候不行?

我问是因为我的一个组件需要安装三个 ref 才能调用 DOM API。其中两个必需的引用是通过 JSX ref 在同一组件中分配的“普通”引用。支柱。稍后将通过 React 上下文将另一个 ref 分配到深度嵌套的组件中。我需要一种方法来在所有三个 ref 都安装后强制重新渲染父组件,并强制 useEffect卸载任何引用时进行清理。

最初我编写了自己的回调 ref 处理程序,它调用了 useState我存储在上下文提供程序中的 setter 。但后来我意识到 useState setter 做了我自己的回调 ref 所做的一切。仅使用 setter 而不是编写我自己的回调 ref 函数是否安全?还是有更好和/或更安全的方法来做我想做的事情?

我尝试用谷歌搜索 "useState" "callback ref" (和其他类似的关键字变体),但结果没有帮助,除了 @theKashey的优秀use-callback-ref我肯定会在其他地方使用的包(例如,当我需要将回调 ref 传递给需要 RefObject 的组件时,或者当我既需要回调又需要在本地使用 ref 时)但在这种情况下,所有回调需要做的是当 ref 改变时设置一个状态变量,所以 Anton 的包在这里看起来有点过分了。

下面是一个简化的示例,位于 https://codesandbox.io/s/dreamy-shockley-5dc74 .

import * as React from 'react';
import { useState, forwardRef, useEffect, createContext, useContext, useMemo } from 'react';
import { render } from 'react-dom';

const Child = forwardRef((props, ref) => {
return <div ref={ref}>This is a regular child component</div>;
});

const refContext = createContext();
const ContextUsingChild = props => {
const { setValue } = useContext(refContext);
return <div ref={setValue}>This child uses context</div>;
};

const Parent = () => {
const [child1, setChild1] = useState(null);
const [child2, setChild2] = useState(null);
const [child3, setChild3] = useState(null);

useEffect(() => {
if (child1 && child2) {
console.log(`Child 1 text: ${child1.innerText}`);
console.log(`Child 2 text: ${child2.innerText}`);
console.log(`Child 3 text: ${child3.innerText}`);
} else {
console.log(`Child 1: ${child1 ? '' : 'not '}mounted`);
console.log(`Child 2: ${child2 ? '' : 'not '}mounted`);
console.log(`Child 3: ${child3 ? '' : 'not '}mounted`);
console.log(`In a real app, would run a cleanup function here`);
}
}, [child1, child2, child3]);

const value = useMemo(() => ({ setValue: setChild3 }), []);

return (
<refContext.Provider value={value}>
<div className="App">
This is text in the parent component
<Child ref={setChild1} />
<Child ref={setChild2} />
<ContextUsingChild />
</div>
</refContext.Provider>
);
};

const rootElement = document.getElementById('root');
render(<Parent />, rootElement);

最佳答案

每次出现目标元素时,您都会有额外的重新渲染(因为它可能会被有条件地渲染,它可能会发生不止一次)。
否则它应该工作得很好。除了,它可能会让 future 的代码读者感到困惑。
我宁愿使用额外的功能 + useRef减少认知负担(又名“困惑”)。甚至更多:我们可能不需要回调引用,因为我们有 useEffect :

const childRef = useRef();

useEffect(() => {
... do something
}, [childRef.current]);

<div ref={childRef} ...
但可以肯定的是,在非常普遍的情况下,这可能不适合我们,因为回调 ref每个目标元素的生命周期只调用两次,而 useEffect如果列表中有更多依赖项,则可能会更频繁地触发。但还是。

关于reactjs - 使用 useState "setter"函数作为回调引用是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59243994/

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