重新选择 - 在createSelector中为第二个选择器使用自定义参数

时间:2018-06-15 15:23:19

标签: javascript reactjs redux reselect

我有以下案例:

const firstSelector = (store, userId) => { ... };

const secondSelector = (store, moneyId) => { ... };

const selector = createSelector(
   firstSelector,
   secondSelector, //      it doesn't accept `userId` but `moneyId` which is inside 
                   //      `firstSelector` (first.moneyId)
   (first, second) => { ... },
);

正如你所看到的,只要我能将自定义参数传递给第二个选择器,一切都会很棒。

secondSelector接受moneyId作为第二个参数,实际上是first.moneyId

我的问题:

我可以在第二个组合选择器上使用参数,这实际上是firstSelector返回的值吗?

1 个答案:

答案 0 :(得分:1)

const firstSelector = (store, userId) => ({ moneyId: 'moneyIdFromFirst' });
const secondSelector = (store, moneyId) => ({ second: 'selector', moneyId });

const intermediateSelector = (store, userId) => createSelector(
  firstSelector,
  (first) => secondSelector(store, first.moneyId)
)(store, userId)

const selector = createSelector(
  firstSelector,
  intermediateSelector,
  secondSelector, // not longer necessary
  (first, second, third) => 
    console.log(first, second, third)
);

实现输出:

Object { moneyId: "moneyIdFromFirst" }
Object { second: "selector", moneyId: "moneyIdFromFirst" }
Object { second: "selector", moneyId: "userId" }

intermediateSelector返回值moneyIdFromFirst而不是secondSelector' s userId

感谢@Joseph Sikorski,您可以使用简约的单功能解决方案:

const selectorOneFunc = createSelector(
  firstSelector,
  (state, userId) =>
    secondSelector(state, firstSelector(state, userId).moneyId),
  (first, second) =>
    console.log("selectorOneFunc:", first, second)
);

Edit oz9wnlrny