【问题标题】:How can i memoize a value of `useSelector()`?我怎样才能记住`useSelector()`的值?
【发布时间】:2025-12-22 12:35:10
【问题描述】:

我的代码如下所示:

const countersSelector = () => (store) => store.counters;

const MethodOne = () => {
  // Method: Object destructuring
  const counters = useSelector(countersSelector);

  console.log("render MethodOne");

  useEffect(() => {
    console.log("in useeffect methodone");
  }, [counters]);

  return (
    <div>
      <p>{`firstCounter: ${counters}`}</p>
      <p>{`renders: ${renderCount}`}</p>
    </div>
  );
};

export default MethodOne;

这是完整的应用程序: https://codesandbox.io/s/redux-useselector-object-destructuring-example-forked-1m87x

并且每次counters 对象被更改(不是它的值,而是对象引用本身),useEffect() 都会被触发。

我可以以某种方式记住它,这样counters 只会在store.counters 的实际值改变时才会改变?

【问题讨论】:

    标签: redux css-selectors redux-toolkit


    【解决方案1】:

    我不确定你在这里要求什么。

    state.counters 更改为新的对象引用是不可变更新的工作方式。 Immutable updates always require updating _all nested fields。因此,如果该操作应该更新rootState.counters.firstCounter,则需要为counters 创建一个新对象,并为rootState 创建一个新对象。

    所以,如果您的选择器是state =&gt; state.counters,那么useSelector 在每次counters 对象更改为新引用时重新渲染组件,useEffect 将重新运行因为它的依赖数组中有一个新的引用,这正是它应该如何工作的

    附带说明,您的countersSelector 不正确。它被写成一个“工厂函数”,返回一个选择器。这意味着useSelector 实际上会查看新函数引用,而不是从状态中提取的值

    相反,它应该只是state =&gt; state.counters

    【讨论】: