从 redux-saga 调用组合的重新选择选择器
Call combined reselect selector from redux-saga
我正在尝试从 redux-saga
调用组合选择器。我的想法是我有两个下拉菜单。第一个下拉列表中的选择将在第二个下拉列表中过滤出适当的值,即我的组合选择器将过滤掉一些不相关的值,因此它们不会显示在第二个下拉列表中:
1) 我有两个选择器,firstSelector
和 secondSelector
// firstSelector returns {"Cat":["black","white"],"Dog":["grey"]}
const firstSelector= () =>
createSelector(selectPage, substate => substate.firstDropDown);
// secondSelector returns ["black","grey"]
const secondSelector= () =>
createSelector(selectPage, substate => substate.secondDropDown);
2) 我将它们组合在组合选择器中(应该 return ["black", "grey"]
,即 "white" 被过滤掉)
const filterBySelection = (firstSelector, secondSelector) =>
createSelector(
[
firstSelector,
secondSelector,
],
(first, second) => {
const filteredValues = Object.keys(first).reduce(
(r, k) => r.concat(first[k]),
[],
);
return second.filter(val => filteredValues.indexOf(val) >= 0);
},
);
3) 但是如何在 redux-saga
中调用 filterBySelection
?
我试过了:
const filteredValues = yield select(
filterBySelection,
firstSelector,
secondSelector,
);
和
const filteredValues = yield select(
filterBySelection(firstSelector, secondSelector)()
);
和
const filteredValues = yield select(
filterBySelection(firstSelector, secondSelector)
);
但是这些方法都行不通。
不过,我可以调用 firstSelector
或 secondSelector
,即有效:
const firstData= yield select(firstSelector());
有人会说我可以在 redux-saga 中简单地执行以下操作:
const first = yield select(firstSelector());
const second = yield select(secondSelector());
const filtered = Object.keys(first).reduce(
(r, k) => r.concat(first[k]),
[],
);
const secondFiltered = second.filter(
val => first.indexOf(val) >= 0,
);
但这会 not memoize
并且想法是 memoize
。
那么可以在 redux-saga 中使用记忆选择器吗?
此致
您似乎错过了对 return 选择器的函数调用。所以,要么:
一)
const filterBySelection = (firstSelector, secondSelector) =>
createSelector(
[
firstSelector(), // <- parentheses
secondSelector(), // <- parentheses
], ... )
然后:const filteredValues = yield select(
filterBySelection(firstSelector, secondSelector)
);
b) 正确传递选择器
const filteredValues = yield select(
filterBySelection(firstSelector(), secondSelector())
);
c) 定义没有函数的firstSelector
和secondSelector
(也许是最真实的方式):
const firstSelector =
createSelector(selectPage, substate => substate.firstDropDown);
const secondSelector =
createSelector(selectPage, substate => substate.secondDropDown);
然后
const filteredValues = yield select(
filterBySelection(firstSelector, secondSelector)
);
希望对您有所帮助。
我会选择这样的东西
createSelector(
firstSelector,
secondSelector,
(first, second) => {
const filteredValues = Object.keys(first).reduce(
(r, k) => r.concat(first[k]),
[],
);
return second.filter(val => filteredValues.indexOf(val) >= 0);
},
);```