假设我想要来自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
达到相同的结果
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;
您可以对您的状态使用解构分配,例如:
const { reducer1, reducer2, reducer3 } = useSelector((state: any) =>
({
reducer1: state?.reducer1,
reducer2: state?.reducer2,
reducer3: state?.reducer3
}));
我在这里回答我的问题。
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);