【问题标题】:NGRX: how to call factory selectors from within other selectorsNGRX:如何从其他选择器中调用工厂选择器
【发布时间】:2022-01-20 01:08:28
【问题描述】:

由于 NGRX deprecated selectors with props 在版本 11 中。使用属性的预期方法是创建工厂选择器,

  • 如何嵌套选择器,或者从另一个调用一个并在它们之间传递状态?

改变之前,有以下两个选择器

export const selector1 = createSelector(
   state,
   ( state: FormState, props: {id: string} ) => {
       // Return items whose parent match the given id
       return state.items.filter( item => item.parentId === props.id);
   }
);

export const selector2 = createSelector(
    state
    ( state, FormState, props: { id: string} ) => {
       return state.notes.filter( note => note.parentId === props.id);
    }
)

您可以从另一个选择器中调用其中一个,如下所示

export const selector3 = createSelector(
   state,
   ( state: FormState, props: {id: string} ) => {
       // get notes by using an existing selector and passing the state & properties
       const notes = selector2({ storeName: state}, props)
       // do some more logic based on the nested call to a selector
       ...
   }
);

现在工厂选择器是处理属性时的预期格式,选择器现在看起来像下面这样

export const selector1 = (id: string) => createSelector(
   state,
   ( state: FormState ) => {
       // Return items whose parent match the given id
       return state.items.filter( item => item.parentId === id);
   }
);

export const selector2 = (id: string) => createSelector(
    state
    ( state, FormState ) => {
       return state.notes.filter( note => note.parentId === id);
    }
)
  • 给定工厂选择器,有没有办法从selector1 中调用selector2
  • 如果是,状态是如何传递给嵌套选择器的

例如

export const selector3 = (id: string) => createSelector(
   state,
   ( state: FormState ) => {
       // how is the `state` passed to the nested selector call below? 
       const notes = selector2( id)
   }
);

谢谢。

【问题讨论】:

    标签: angular ngrx ngrx-selectors


    【解决方案1】:

    createSelector 函数可以接收其他选择器作为参数。

    所以你可以这样做:

    export const selector3 = (id: string) => createSelector(
       state,
       select2(id),
       (state: FormState, filteredNotes ) => {
    
           const notes = filteredNotes;
       }
    );
    

    【讨论】:

    • 感谢您的回复。我在其他一些选择器中使用这种方法。但我想知道是否有一种方法可以调用选择器,而不是将其作为参数包含在内?即允许在调用选择器之前应用条件业务逻辑。即在调用选择器之前检查id 参数是否有效...
    • 不确定是否通过有条件地应用选择器获得显着的性能改进,它们是非常精益的函数。您可以调用所有需要的选择器作为参数,而不是选择性地使用它们的值。
    猜你喜欢
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多