![](/img/trans.png)
[英]Angular 2 ngrx : how to update an array which is embedded in one the the items of my state array?
[英]How to update only one object property or multiple in an array using ngrx state in Angular 5?
我有一個要存儲在狀態中的元素數組,該數組看起來像這樣:
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
更改為selected
,甚至將更多對象添加到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函數“查找”來完成此操作。
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"}
filters
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';
我相信您可以在此示例中為每種需要創建一個函數。 這不會更改整個數組。
完成如果過濾器類別發生更改,請使用函數將filtercategory名稱的值傳遞給自定義數組更新函數。 如果它屬於某個過濾器類別的過濾器中的內容,則也可以通過。 函數可以像okThisChanged(filtercategory,value,newStatus)
進行編輯,而okThisFilterAdded(filtercategory,newlyAddedFilter)
進行添加
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.