gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:52:57 26 4
gpt4 key购买 nike

我有以下案例:

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 返回的值?

最佳答案

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 而不是 secondSelectoruserId

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

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

Edit oz9wnlrny

关于javascript - 重新选择 - 在 createSelector 中为第二个选择器使用自定义参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50878544/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com