使用重新选择有条件地组成选择器

Conditionally composing a selector using reselect

export const mySelector = createSelector(
    [selectorA, selectorB], // but I want selectorB or selectorC to be chosen here using logic
    (foo, bar) => {
        // ...
    }
);

我想在基于商店中的状态(即另一个选择器返回的值)创建此选择器时有条件地使用 selectorBselectorC

我该怎么做?

然后制作一个 selectorCorB 组成 selectorB, selectorC , selectorX

selectorX 是存储中变量 x 的选择器,它决定 selectorB 或 selectorC

const selectorCorB = createSelector(
  selectorB,
  selectorC,
  selectorStateX,
  (b, c, x) => x? b: c
) 

mySelector = createSelector(
    [selectorA, selectorCorB], // will be A AND B OR C depending on x
    (foo, cOrb) => {
        // ...
    }
);

只是指出接受的答案中建议的方法将评估每个 上的 selectorBselectorC selectorCorB 调用。这可能不是期望的行为。

实际的条件调用可能是这样实现的:

export const selectorCorB = createSelector(
    selectorStateX
    (...arguments) => arguments,
    (x, arguments) => x ? selectorB(...arguments) : selectorC(...arguments)
);