gpt4 book ai didi

reactjs - 使用对象解构使用 useSelector() 钩子(Hook)从 redux 状态中提取特定值是否安全

转载 作者:行者123 更新时间:2023-12-05 01:07:33 26 4
gpt4 key购买 nike

使用 useReducer() 钩子(Hook)从 redux 状态中提取特定值是否安全,如下所示:

const {item1, item2, item3} = useSelector(state => state);

或者这会导致问题(关于重新渲染和状态),还是被认为是不好的做法?

最佳答案

你不应该永远从选择器返回整个state!

根据文档,useSelector re-renders any time the selector return value changes after a dispatch .因此,重要的是 each call to useSelector should return the smallest possible piece of state this component needs .

在这种情况下,最好的选择是三个单独的 useSelector 调用,每个调用都返回一个字段,或者一个 useSelector 调用只提取这些字段并返回它们.然而,因为返回一个新的对象引用会导致重新渲染,你要么需要 use the shallowEqual comparison functiona memoized selector function一起返回这些字段时避免不必要的重新渲染。

关于reactjs - 使用对象解构使用 useSelector() 钩子(Hook)从 redux 状态中提取特定值是否安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67319325/

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