useSelector 导致多次重新渲染

useSelector causes multiple re-renders

当使用 react-devtools 时,它告诉我我的根组件重新渲染的原因是因为 hooks 改变了?

当我删除任何 useSelectors 时,我的根组件只呈现一次,启用后它呈现 6 次。

对于发生这种情况的原因有哪些猜测?

import {
  /// Data State Constants...
  SET_USER_DATA,
  SET_BADGE_COUNT,
} from "../Actions/gameState";

const initialState = {
  /// Data state...
  userData: [],
  badgeCount: 0,
};

export default function gameState(state = initialState, action) {
  const { type, payload } = action || {};
  switch (type) {
    /////////////////////////
    /// Data state Reducers...
    /////////////////////////
    case SET_USER_DATA: {
      return { ...state, userData: payload };
    }
    case SET_BADGE_COUNT: {
      return { ...state, badgeCount: payload };
    }

    default:
      return state;
  }
}

好的,问题是:useSelector 将新值与旧值进行严格的 === 比较。您可以为每个字段调用一个 useSelector 或从 react-redux:

实现 shallowEqual
const someState = useSelector(state=>state.myState.someState, shallowEqual)

这里是文档: https://react-redux.js.org/next/api/hooks#equality-comparisons-and-updates