我有以下案例:
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
返回的值吗?
答案 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)
);