Job*_*obz 8 ngrx angular ngrx-store ngrx-reducers
我有一个带有对象数组的 ngrx 商店。我正在寻找的是,使用数组索引更新(修改)数组内的对象。我的 ngrx 数据看起来像,
policies: {
beneficiaries: {
beneficiaries: [{
name: 'pqr'
age: 56
},
{
name: 'xyz'
age: 76
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
我必须根据数组索引更新受益人姓名。所以我实现了以下reducer功能
on(policiesActions.updateBeneficiaryPercentage, (state, action) => {
return {
...state,
beneficiaries: {
...state.beneficiaries,
beneficiaries: {
...state.beneficiaries.beneficiaries,
[action.index]: {
...state.beneficiaries.beneficiaries[action.index],
name: action.value
}
}
}
};
})
Run Code Online (Sandbox Code Playgroud)
上面代码的问题是,运行这段代码后,我的商店结构变成了
policies: {
beneficiaries: {
beneficiaries: {
0: {
name: 'pqr'
age: 1000
},
1: {
name: 'xyz'
age: 76
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
请帮我修复代码,以便我可以在不改变存储结构的情况下更新值。
使用Array.map方法:
arr.map((value, index) => index === action.index ? {...value, name: action.value} : value)
Run Code Online (Sandbox Code Playgroud)
或者只使用ngrx-etc,它可以让你以可变的方式改变你的状态,同时保持不可变
mutableOn(onAction, (state, action) => {
state.arr[action.index].name = action.name
return state
})
Run Code Online (Sandbox Code Playgroud)
这是一种简单的方法,无需深入研究状态对象。
on(ProductActions.updateProductSuccess, (state, action): ProductState => {
// define a constant and map over the existing state, inserting your new item,
// then assign your new object as the new state.
const updatedProducts = state.products.map(
product => action.product.id === product.id ? action.product : product);
return {
...state,
products: updatedProducts
};
}),
Run Code Online (Sandbox Code Playgroud)
这假设您在成功操作中传递了完整的产品对象。
更新数组中的对象时,我会重新创建一个包含所有排除对象的数组,并附加需要更新值的最后一个对象。
const policies = {
beneficiaries: {
beneficiaries: [{
name: 'pqr',
age: 56
},
{
name: 'xyz',
age: 76
}
]
}
}
const updateObject = (state, action) => {
if(!state.beneficiaries.beneficiaries[action.index]) {
return state;
}
return {
...state,
beneficiaries: {
...state.beneficiaries,
beneficiaries: [
...state.beneficiaries.beneficiaries.slice(0, action.index),
{
...state.beneficiaries.beneficiaries[action.index],
name: action.value
},
...state.beneficiaries.beneficiaries.slice(action.index + 1)
]
}
};
}
console.log(updateObject(policies, {index: 1, value: 'test'}))Run Code Online (Sandbox Code Playgroud)
- 编辑
添加了代码片段并更改了逻辑,因此它不会更改列表顺序。
| 归档时间: |
|
| 查看次数: |
4774 次 |
| 最近记录: |