我正在使用 redux-react 从 redux 商店获取物品。很多组件都有这样的 useSelector 调用:
const summary = useSelector((state) => state.deliveryOI.summary);
将所有 useSelector 调用移至单独的钩子并通过解构从中获取项目是否有益?这种方式看起来更好并且更具可读性,但我担心性能。例如:
import { useSelector } from "react-redux";
const useOISelector = () => {
const currentOption = useSelector((state) => state.deliveryOI.currentOption);
const currentTableRowIndex = useSelector(
(state) => state.deliveryOI.currentTableRowIndex
);
const deliveryDates = useSelector((state) => state.deliveryOI.deliveryDates);
const isConfirmationError = useSelector(
(state) => state.deliveryOI.isConfirmationError
);
const isCutOffTime = useSelector((state) => state.deliveryOI.isCutOffTime);
const summary = useSelector((state) => state.deliveryOI.summary);
const tableRows = useSelector((state) => state.deliveryOI.tableRows);
const tabsForm = useSelector((state) => state.deliveryOI.tabsForm);
return {
currentOption,
deliveryDates,
isConfirmationError,
isCutOffTime,
summary,
tableRows,
tabsForm,
currentTableRowIndex,
};
};
export default useOISelector;
并这样称呼它:
const { tableRows, isCutOffTime, currentTableRowIndex } = useOISelector();
如果可读性和简单性是您的主要目标,那么合并选择器可能是值得的。但是,如果性能至关重要,请考虑以下策略:
记忆组合选择器:您可以使用像
reselect
这样的库创建单个组合选择器,该库仅在状态的相关部分发生变化时重新计算值,从而减少不必要的重新渲染。
import { createSelector } from 'reselect';
const selectDeliveryOI = (state) => state.deliveryOI;
export const selectOIState = createSelector([selectDeliveryOI], (deliveryOI) => ({
currentOption: deliveryOI.currentOption,
currentTableRowIndex: deliveryOI.currentTableRowIndex,
deliveryDates: deliveryOI.deliveryDates,
isConfirmationError: deliveryOI.isConfirmationError,
isCutOffTime: deliveryOI.isCutOffTime,
summary: deliveryOI.summary,
tableRows: deliveryOI.tableRows,
tabsForm: deliveryOI.tabsForm,
}));
然后,在
useOISelector
中这样使用它:
import { useSelector } from 'react-redux';
import { selectOIState } from './selectors';
const useOISelector = () => useSelector(selectOIState);
export default useOISelector;
针对状态的不同部分使用单独的钩子:您可以为状态的不同部分(例如,useDeliveryDates、useTableRows)创建较小的自定义钩子,而不是将所有状态选择合并到单个钩子中,以便组件只能订阅特定的钩子他们需要的数据片段,减少重新渲染。