我们如何在 Redux 中组合选择器?

问题描述 投票:0回答:3

假设我想要来自3个不同reducer的3个数据。

一般来说我可以做这样的事情!!

const data1 = useSelector((state: any) => state?.reducer1);
const data2 = useSelector((state: any) => state?.reducer2);
const data3 = useSelector((state: any) => state?.reducer3);

那么我怎样才能用单个

useSelector

达到相同的结果
reactjs react-native react-redux redux-toolkit redux-thunk
3个回答
1
投票
const dataState = useSelector((state: any) => ({reducer1: state?.reducer1, reducer2: state?.reducer2, reducer3: state?.reducer3}));

const data1 = dataState.reducer1;
const data2 = dataState.reducer2;
const data3 = dataState.reducer3;

0
投票

您可以对您的状态使用解构分配,例如:

const { reducer1, reducer2, reducer3 } = useSelector((state: any) =>
  ({
    reducer1: state?.reducer1,
    reducer2: state?.reducer2,
    reducer3: state?.reducer3
  }));

0
投票

我在这里回答我的问题。

import {createSelector} from 'reselect';    

   const combinedSelector = createSelector(
     (state: any) => state?.reducer1,
     (state: any) => state?.reducer2,
     (state: any) => state?.reducer3,
     (state: any) => state.reducer4,
      (reducer1, reducer2, reducer3, reducer4) => ({
        data1: reducer1?.data1,
        data2: reducer2?.data2,
        data3: reducer3?.data3,
        data4: reducer4?.data4,
      }),
    );

 const {data1, data2} = useSelector(combinedSelector);
© www.soinside.com 2019 - 2024. All rights reserved.