代码之家  ›  专栏  ›  技术社区  ›  Thiago Rodrigues

从Reducer调用选择器

  •  2
  • Thiago Rodrigues  · 技术社区  · 7 年前

    我可以使用减速器中的选择器吗?

    我有一个类似的代码:

        case Action Types.ACTION: {
              const loading = getIsLoading(state) 
               return {
                   atribute1: false,
                   attribute2: action.payload,
               }
           }
    
           default: {
    
               return state;
    
           } 
    
       }
    
    }
    
    
    export const getState = createFeatureSelector<State>('feature');
    
    export const getIsLoading = createSelector(
    
       getState,
    
       state => state.loading
    
    );
    

    当我首先调度一个动作时,我会遇到这样一个错误:“无法读取未定义的‘加载’”。

    我的错在哪里?我的方法有问题吗?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Adrian Fâciu    7 年前

    正如我在评论中所说: 最好不要在该州复制信息。 如果您需要调用减速机中的选择器,看起来您可以这样做。

    您可以通过创建第三个更高阶的reducer来避免这样做,该reducer将从现有的reducer中返回所需的任何内容。

    因此,您有了getIsBusy reducer,并创建了另一个reducer,它只会返回您所在州的新数据,即您想要读取的isBusy:

    export const getAttribute = createSelector(
       getState,
       state => state.attribute
    
    );
    

    现在您有了getIsBusy和getAttribute作为选择器,可以创建第三个选择器,在其中可以放置所需的逻辑:

    export const getHigherOrderSelector = createSelector(
       getIsBusy,
       getAttribute,
       (isBusy, data) => {
          return { isBusy, data };
          // Or whatever other processing you might want to do here
       }
    );