我正在尝试更新深层嵌套的json属性,但我无法这样做。我尝试了几种方法,有人有任何想法吗?
方式1:不起作用......
case ADD_REWARD:
console.log("state", state);
console.log("reward index", action.index);
return {
...state,
rewards: [
{
...state.rewards[action.index],
value: {
...state.rewards[action.index].value[0],
target: [
...state.rewards[action.index].value[0].target,
initialState.value_key_pair
]
}
}
]
};
方式2:有效,除了它为不需要的对象添加索引...
case ADD_REWARD:
console.log("state", state);
console.log("reward index", action.index);
return {
...state,
rewards: [
{
...state.rewards,
[action.index]: {
...state.rewards[action.index],
value: {
...state.rewards[action.index].value,
[0]: {
...state.rewards[action.index].value[0],
target: [
...state.rewards[action.index].value[0].target,
initialState.value_key_pair
]
}
}
}
}
]
};
我希望这种状态在不可更新后更新。
rewards: [
{
type: "group",
operand: "AND",
value: [
{
type: "discount",
subtype: "percent",
value: 20,
target: [
{
type: "abc",
value: "123"
},
{
type: "def",
value: "456"
}
]
}
]
}
]
答案 0 :(得分:0)
这是我在经过一些发现之后想出来的。
return {
...state,
rewards: state.rewards.map((group,index) => index === action.index ?
// transform the one with a matching id
{ ...group, value: [...group.value.map((reward, index) => index === 0 ?{
...reward,
target: [...reward.target, initialState.value_key_pair]
} :reward
)]
} : group
),
}