gpt4 book ai didi

reactjs - react Hook : activable states patterns

转载 作者:行者123 更新时间:2023-12-03 14:17:48 25 4
gpt4 key购买 nike

我正在尝试创建一个可以根据 Prop 激活/禁用某些功能的组件。所有这些功能都需要一个必须管理的状态。

我试图考虑一种可能的模式,该模式允许我们在连接的功能未激活的情况下不创建状态。我想到了两种可能的方法:

方式#1

function useFunctionality(initState, enable) {
if (!enable) {
return null;
}

const [funct, updateFunct] = useState(init);
return funct;
}

function Component({ enableFunct }) {
const funct = useFunctionality('test', enableFunct);
return (...);
}

方式#2

function useFunctionality(initState, enable) {
const [funct, updateFunct] = useState(init);
return enable ? funct : null;
}

function Component({ enableFunct }) {
const funct = useFunctionality('test', enableFunct);
return (...);
}

在这两种情况下,钩子(Hook)都会继续工作。问题是:你觉得哪种方式更正确?有更好的方法吗?

最佳答案

两种食谱都有问题。

方式 1 可能允许在组件渲染时有条件地调用钩子(Hook),这可能会导致错误,即 discouraged :

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.

this answer 中所述,这个规则可以被丢弃,只要保证渲染之间条件不会改变。

保证这一点的一种方法是记住一个条件:

function useFunctionality(initState, enable) {
const condition = useMemo(() => enable, []);

if (!condition)
return null;

const [funct, updateFunct] = useState(initState);
return funct;
}

方式 2 更可取,因为它更干净,而且 useState 调用并不昂贵。

这两种方式都有同样的问题,它们使用的状态永远不会改变。如果这是意图,那么这就是 ref 的用例。由于它永远不会改变,因此可以放置一个条件作为初始值:

function useFunctionality(initState, enable) {
return useRef(enable ? initState: null).current;
}

关于reactjs - react Hook : activable states patterns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55278771/

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