我在reducer中將以下json文件保存在客戶端狀態中。現在,當我通過ajax添加新的Notes時,我打電話給NEW_NOTE_SUCCESS reducer,它假設將新音符添加到現有音符數組中。Redux Reducer - 向嵌套狀態添加新數據
export default function clientProfile(state={}, action) {
switch(action.type) {
case NEW_NOTE_SUCCESS:
console.log(action.payload);
return { ...state, notes: [...state.notes, action.payload] }
default:
return state;
}
}
但是,在我做了上述之後,this.props.client.notes將只有我添加的新筆記,但不是舊筆記。
我該如何將新音符「推」到數組中,所以我不需要在每次添加新音符時重新發送音符json文件。
PS:action.payload包含以下json。
{
"noteId": "10000000",
"customerId": "34",
"createdBy": "1",
"created": "1510316194",
"note": "ADDED A NEW NOTE. NEED TO ADD TO STATE"
}
這是原始負載中的json文件。
{
"customerId": "34",
"agentId": "1",
"createdDate": "1510223892",
"firstname": "John",
"lastname": "Doe",
"mobile": "123456789",
"address": "Something email here",
"notes": {
"0": {
"noteId": "1",
"customerId": "34",
"createdBy": "1",
"created": "1510316194",
"note": "add something"
},
"1": {
"noteId": "2",
"customerId": "34",
"createdBy": "1",
"created": "1510316527",
"note": "add something"
},
"2": {
"noteId": "3",
"customerId": "34",
"createdBy": "1",
"created": "1510317177",
"note": "add new thing"
},
"3": {
"noteId": "4",
"customerId": "34",
"createdBy": "1",
"created": "1510318448",
"note": "something"
},
"4": {
"noteId": "5",
"customerId": "34",
"createdBy": "1",
"created": "1510318476",
"note": "this would be note number 5, lets see whether we can get something from this."
}
}
}
更新:Reducer Codes - Object而不是數組。
case NEW_NOTE_COMPLETE:
return { ...state, notes: {...state.notes, action.payload.noteId: action.payload} }
當你得到一個注意到的'3'一個鍵,你已擁有該鍵的音符會發生什麼?你需要覆蓋它還是更改新筆記的密鑰? –
只有noteId是唯一的,所以我只是推入陣列鍵5例如 –
嗯,在我看來,你有混合的數據結構。你看,在你的json文件中'notes'是一個對象,但在你的reducer中它是一個數組。我希望看到這行'注意:{... state.notes,「someKey」:action.payload}'而不是這個'注意:[... state.notes,action.payload]' –