ngrx:如何将参数传递给createSelector方法中的选择器 [英] ngrx: how to pass parameters to selector inside createSelector method

查看:87
本文介绍了ngrx:如何将参数传递给createSelector方法中的选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

商店中的状态非常简单:

I have a very simple state in my store:

const state = {
 records: [1,2,3],
};

我有一个记录选择器:

export const getRecords = createSelector(getState, (state: State) => state.records));

我现在想要的是具有单独的选择器,用于按索引获取每个记录. 为此,我想通过以下方式用道具创建一个通用选择器:

And what I want now is to have separate selectors for fetching each record by index. For this purpose I want to create one generic selector with props in this way:

export const getRecordByIndex = createSelector(
getRecords,
(state: State, { index }) => state.records[index]),
);

然后创建几个特定的​​选择器e. g.:

And after that create a couple of specific selectors e. g.:

export const getFirstRecord = createSelector(
getRecordByIndex(/* somehow pass index = 0 to this selector */),
(firstRecord) => firstRecord),
);

但是当我们在createSelector方法中使用参数时,我没有发现如何将参数传递给带有道具的选择器.有可能吗?

But I didn't find any mention how to pass parameters to selectors with props when we use them inside createSelector method. Is it possible?

推荐答案

来自此博客文章: https://blog.angularindepth.com/ngrx-parameterized-selector-e3f610529f8

从NgRx 6.1开始,选择器还接受一个额外的props参数.哪个 意味着您现在可以定义一个选择器,如下所示:

As of NgRx 6.1 selectors also accepts an extra props argument. Which means you can now define a selector as the following:

export const getCount = createSelector(
  getCounterValue, 
  (counter, props) => counter * props.multiply
);

this.counter = this.store.pipe(
  select(fromRoot.getCount, { multiply: 2 })
);

啊...但是重新阅读您的问题,您在问然后如何构建使用该选择器的另一个选择器?上面链接的文章建议构建工厂功能.

Ah ... but rereading your question, you are asking then how to build another selector that uses this selector? The above-linked article suggests building a factory function.

这篇关于ngrx:如何将参数传递给createSelector方法中的选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆