useSelector导致多次重新渲染

时间:2020-10-02 21:47:04

标签: react-native redux reducers

使用react-devtools时,它告诉我重新渲染根组件的原因是因为钩子已更改?

当我删除任何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;
  }
}

1 个答案:

答案 0 :(得分:1)

好吧,事情是:useSelector使用严格的===将新值与旧值进行比较。您可以在每个字段中调用一个useSelector,也可以在shallowEqual中实现react-redux

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

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