javascript - 如何使用 Angular 5 中的 ngrx 状态仅更新一个对象属性或数组中的多个对象属性?

标签 javascript arrays angular ngrx

我有一个元素数组,我将其存储在一个状态中,该数组看起来像这样:

filterList: Array<any> = [
    {name: "Branch", filters: [{value: "Location 1", status: "unselected"}, {value: "Location 2", status: "selected"}]},
    {name: "Segment", filters: [{value: "Segment 1", status: "selected"}, {value: "Segment 2", status: "selected"}]},
     ...... and so on
]

数组是一个巨大的列表,我想在其中添加一个对象到filters数组或将status属性从unselected更改选定的,甚至将更多对象添加到filterList

如何设置状态,以仅更改我需要的内容而不更改整个数组?到目前为止,我已经尝试了一些事情,但无法解决。 这是我尝试过的。

case FilterActions.FILTER_LIST:
   return {
      ...state,
      filterList: [...state, action.payload]
   };

而且我如何调度操作来一次只更新几个元素? 我一直在尝试这样做。

this.store.dispatch(new MainActions.FilterListActions([{name: "Branch"}, filters: [{value: "Location 1", status: "selected"}]]));

请帮我解决这个问题。

更新

这是store.actions.ts的代码

import {Action} from '@ngrx/store';

export const FILTER_LIST = 'FILTER_LIST';

export class FilterListAction implements Action {
  readonly type = FILTER_LIST;
  constructor (public payload: Array<any>) {}
}

export type FilterActions = FilterListAction;

以下是 store.reducer.ts 文件的代码:

import * as FilterActions from './store.actions';

const initialState = {
  filterList: []
};

export function filtersReducer(state = initialState, action: FilterActions.FilterActions) {
  switch (action.type) {
     case FilterActions.FILTER_LIST:
        return {
          ...state,
          filterList: [...state, action.payload]
        };
     default: return state;
  }
}

最佳答案

我相信您可以使用简单的 js/ts 函数“find”来完成此任务。

let filterList: Array<any> = [
    {name: "Branch", filters: [{value: "Location 1", status: "unselected"}, {value: "Location 2", status: "selected"}]},
    {name: "Segment", filters: [{value: "Segment 1", status: "selected"}, {value: "Segment 2", status: "selected"}]},
     ...... and so on
]

考虑需要添加对象的情况

  let toBeAddedFilter = {value: "Location 1", status: "unselected"}

过滤器,其中name=“Branch”

然后你使用filter()就像

filterList.find(x=>x.name=="Branch").filters.push(toBeAddedFilter);

还可以更改特定分支的一个特定位置的状态

filterList.find(x=>x.name=="Branch")
    .filters.find(y=>y.value="Location 1").status ='selected';

我相信您可以从这个示例中为每种需求创建一个函数。这不会更改完整的数组。

完成 如果过滤器类别发生更改,请使用函数将过滤器类别名称的值传递到自定义数组更新函数。如果它是某个过滤器类别的过滤器内的内容,也可以通过。 这些功能可以类似于用于编辑的 okThisChanged(filtercategory,value,newStatus) 和用于添加的 okThisFilterAdded(filtercategory,newlyAddedFilter)

关于javascript - 如何使用 Angular 5 中的 ngrx 状态仅更新一个对象属性或数组中的多个对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48002252/

相关文章:

javascript - 检查某些属性是否有值

c++ - 使用 sizeof() 计算数组大小

javascript - Angular 2输入时间不返回秒

javascript - 错误: Failed to load resource: the server responded with a status of 404 (Not Found)

javascript - 使用 onscroll 动态更改 div 的高度不起作用

java - 在java中向后排列数组

angular - 如何在 Angular 中的一个元素上应用多个模板绑定(bind)

html - 如何将 contentchildren 的每个 child 包装在 Angular 中自己的元素中

javascript - Bootstrap 模态验证

java - 有没有办法填充 HashMap 中的值以删除文本文件中的特定值?