根据结果​​先前的选择动态定义选择器

时间:2017-07-25 16:10:08

标签: redux reselect

我有选择器从store(filterSelector)获取当前过滤器类型 还有3个,它们使用不同的逻辑从存储中过滤实体,让我们想象它们的名称是smallEntitiesSelector,mediumEntitiesSelector,bigEntititiesSelector。

创建选择器的最佳方法是什么,它将根据商店中的过滤器值返回过滤后的实体?

const filteredEntities = createSelector(
    filterSelector,
    (filterType) => {
        switch filterType: 
           case "small": ???
           case "medium": ???
           case "big": ???  
    }
)

对于这个特定的例子,我会创建一个选择器,它接受filter参数,但实际上我在这个选择器中有更复杂的逻辑,我不想混合它们。

UPD: 由于评论中的请求,我将添加更多代码。这是我如何使它工作的方式:

const filteredEntities = createSelector(
   filterSelector,
   smallEntitiesSelector,
   mediumEntitiesSelector,
   bigEntititiesSelector,
   (filterType, smallEntities, mediumEntities, bigEntities) => {
      switch filterType: 
         case "small": return smallEntities;
         case "medium": return mediumEntities;
         case "big": return bigEntities;  
   }

但是我不喜欢这个解决方案,因为每次原始实体改变时都会执行所有3个选择器,而我只需要执行一个。 所以我的工作,但我觉得有一种方法可以做得更好。

1 个答案:

答案 0 :(得分:1)

作为第一次尝试,您可以设置2个选择器来派生当前过滤器和当前实体数据。然后,将正确的选择器直接调用result function

const filteredEntities = createSelector(
    filterSelector,
    entitiesSelector,   // Todo
    (filterType, entities) => {
        switch filterType: 
           case "small": return smallEntities(entities);
           case "medium": return mediumEntities(entities);
           case "big": return bigEntities(entities);
           // case default?
    }
);

如果您介入性能/缓存失效问题,re-reselect可能会对您有所帮助。

import createCachedSelector from 're-reselect';

const filteredEntities = createCachedSelector(
    filterSelector,
    entitiesSelector,   // Todo
    (filterType, entities) => {
        switch filterType: 
           case "small": return smallEntities(entities);
           case "medium": return mediumEntities(entities);
           case "big": return bigEntities(entities);
           // case default?
    }
)(
    filterSelector
);