【问题标题】:Filtering data in reducer在 reducer 中过滤数据
【发布时间】:2020-08-07 00:02:26
【问题描述】:

我在ngrx中通过reducer排序有问题。

表格已被选择器填满 - 很好。

现在,我想为表数据实现过滤器解决方案 - 包含、开始等。在我看来,最好的解决方案是使用调度程序和操作,并更改减速器中的原始数据 -> 通过选择器更新,在ngOnInit中使用了哪一个。但是有没有可能回到原始数据?什么时候过滤器会是空的?或者在存储中创建重复数据 - 原始数据和过滤数据,并在它们之间切换?

【问题讨论】:

  • 你能用一些实际的代码澄清一下吗?
  • 有对象数组的标准数据表,f.e. [{名称:字符串;数据:数据; name2: string etc...}] 我想按列过滤....

标签: angular ngrx reducers


【解决方案1】:

您可以使用选择器选择原始状态,然后根据您的过滤器进行修改,而不是复制状态本身。

如果这是您想要的,请参考例如取自 official documentation 的内容,它会在某些条件下进行过滤。

export const selectUser = (state: AppState) => state.selectedUser;
export const selectAllBooks = (state: AppState) => state.allBooks;
 
export const selectVisibleBooks = createSelector(
  selectUser,
  selectAllBooks,
  (selectedUser: User, allBooks: Book[]) => {
    if (selectedUser && allBooks) {
      return allBooks.filter((book: Book) => book.userId === selectedUser.id);
    } else {
      return allBooks;
    }
  }
);

【讨论】:

  • 嗯,好主意。但是,当我想拥有“包含”过滤器时。所以最好的方法是带道具的选择器,当道具是“包含字符串”时。但我想知道 - 我将如何动态改变它 - 道具。嗯,在 ngOnInit 中将是一个选择器......但我不会改变它。
【解决方案2】:

您可以将道具传递给选择器

export const selectAllBooks = (state: AppState) => state.allBooks;

export const selectBookById = createSelector(  
  selectAllBooks,
  (allBooks: Book[], props) => {
    const { id } = props;
    return allBooks.filter((book: Book) => book.userId === id);
}

在 ngOnInit 的 Component.ts 中

this.books$ = this.store.pipe(selectBookById, { id: 123 });

【讨论】:

  • 是的,但是哪里有多个列/过滤器?我可以设置两个过滤器(两个道具?)并使用过滤两次,由 f.e.第一和第三列包含
  • 如果我对您的理解正确,您可以传递任意数量的道具并使用香草 javascript 过滤结果,例如 this.store.pipe(selectBookById, { id: 123, name: 'abc', date: '01/05/1983' })
猜你喜欢
  • 1970-01-01
  • 2019-03-11
  • 2017-02-07
  • 1970-01-01
  • 2020-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多