[英]Redux adding nested value to current state
我有以下狀態:
{
list: {
key1: {
value: [{a: 'a'}, {b: 'b'}],
fetching: true
},
key2: {
value: [{c: 'c'}],
fetching: true
}
}
}
我想為某個鍵提供一個新值,並用此替換當前狀態。 但我也希望價值與前一個相結合。 例如,通過以下操作:
key1: {
value: [{d: 'd'}],
fetching: false
}
我會得到以下狀態:
{
list: {
key1: {
value: [{a: 'a'}, {b: 'b'}, {d: 'd'}],
fetching: false
},
key2: {
value: [{c: 'c'}],
fetching: true
}
}
}
我怎樣才能在reducer中做到這一點,以便案例保持不變? (使用...
傳播運算符,而不是ImmutableJS
)。
編輯:
處理(應該)的減速器的一部分:
case "FOO_BAR":
const key = action.payload.key;
const newList = {...state.list};
newList[key] = action.payload.newObject; // {value: ..., fetching: ...}
return {
...state,
list: newList
}
這就是我想要解決它的方式
case "FOO_BAR":
const oldList = {...state.list};
const newKey1Value = action.payload.key.value;
oldList.key1.value = oldList.key1.value.concat(newKey1Value);
const newKey1fetching = action.payload.key.fetching;
oldList.key1.fetching = newKey1fetching;
return {
...state,
list: oldList
}
我希望它對你有所幫助。
您將需要使用spread運算符來傳播舊值,然后傳播newObject [key]值數組。
像這樣的東西:
import { get } from 'lodash';
case "FOO_BAR":
const { key, newObject } = action.payload;
const newList = {
...state.list,
[key]: {
value: [...get(state, 'list[key].value', []), ...newObject[key].value]
fetching: newObject[key].fetching
}
};
return {
...state,
list: newList
}
編輯:我從lodash添加了get
實用程序函數,這樣如果state.list[key]
undefined
,它將返回一個空數組來傳播而不是拋出錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.