4

当我将更多选择器组合在一起时,我发现我正在重新排序选择器的定义位置。例如,

export const selectNav = state => state.nav;
export const selectPage = state => state.page;

export const selectNavAndPage = createSelector([
    selectNav,
    selectPage,
], (nav, page) => {

});

export const selectFoo = state => state.foo;

export const selectNavAndPageAndFoo = createSelector([
    selectNavAndPage,
    selectFoo,
], (navAndPage, foo) => {

});

这是一个简单的示例,但我无法在 selectNavAndPageAndFoo 下定义 selectNavAndPage。随着越来越多的选择器组合起来并且选择器的选择器组合起来,那么我需要确保在使用它们之前在顶部定义所有子选择器。

有没有办法创建这些选择器,这样排序就无关紧要了?

4

3 回答 3

2

我担心同样的问题,我创建了这个 npm 模块define-selectors。这是一个延迟选择器定义的模块,用于解决选择器定义的排序问题,并为其添加其他特性。它尚未稳定,但我将在我的项目中使用它以使其稳定并得到改进。

有关更多信息,请转到github 页面并阅读 README 和源文件。

于 2017-04-25T19:08:13.547 回答
1

I'm pretty sure this is just related to how the ES6 const keyword works. With const, variables do not exist until that line, so if you want to reference a const variable, you need to write that code after the variable declaration. With var, all variables are hosted to the top of the scope.

So, either use var so that you can reference things out of order, or continue using const and define each function in the correct order for usage and references.

于 2017-04-18T16:19:49.123 回答
1

如果您不介意额外输入一点,这里是另一种方法,它需要定义一个“cms”实用函数,该函数包装 createSelector 函数并利用函数提升:

import {createSelector} from 'reselect';

// create memoized selector
function cms(ctx, ...args) {
    if (!ctx.selector) ctx.selector = createSelector(...args);
    return ctx.selector;
}

// define the selectors out of order...

export function getBaz(state) {
    return cms(
        getBaz  // the function itself as context
        , getBar
        , bar => bar.baz
    )(state);
}

export function getBar(state) {
    return cms(
        getBar
        , getFoo
        , foo => foo.bar
    )(state);
}

export function getFoo(state) {
    return state.foo;
}

这不像简单地按顺序定义选择器那样优雅,但也许其他人可以采用这个想法并对其进行改进。

于 2018-02-05T17:03:29.560 回答