网站搜索

javascript - angular ngrx 存储 参数化的记忆化选择器


我阅读了这篇文章 https://blog.angularindepth.com/ngrx-parameterized-selector-e3f610529f8

并且没有找到如何适应以将参数传递到我的选择器中

我尝试将一个 props 对象传递到我的组件中的选择器。

[编辑] 请使用@Julius Dzidzevičius 的解决方案进行回复。

在组件中

this.store.pipe(select(fromRoot.selectors.getPreferences, 'myProps'))

在 AppState 中

const rootSelectors = {
  layout: (state: AppState) => _.get(state, 'layout'),
}

export interface Selectors {
  getPreferences: MemoizedSelectorWithProps<AppState, string, Preference[]>;
}

export const selectors: Selectors = {
  getPreferences: createSelector(
      rootSelectors.layout,
      (state: LayoutState, props: string) 
=> layoutSelectors.preferences(state, props)) 
};

在州

export const layoutSelectors = {
  preferences: (state: LayoutState, props: string) => {
    return state.filter(item => item.name === props)
  },
};

如果有人能告诉我如何通过记忆化选择器将这个参数正确地从组件适配到选择器。

答案#1

你可以这样做

export const getUserById = (userId: string) => createSelector(
    getUserList,
    idList => IdList.filter(id => id === userId)
);

请告诉我你是否仍然有问题

答案#2

记忆化选择器的参数保存在 props 属性下。如下:

(counter) // should be somewhere else but don't know how :(
=> layoutSelectors.preferences(counter))

counter 是来自 rootSelectors.layout 的一个值。无法说出它的具体内容或你的目标是什么,但要在 selector 中访问 props:

(counter, props) => layoutSelectors.preferences(props.counter))