假设我已将数据存储在这样的redux状态
state = {
records : [
{id:"1", name:"foo", city:"A"},
{id:"2", name:"bar", city:"B"},
{id:"3", name:"abc", city:"C"},
]
}
如何使用不可变方式动态更改任何记录的任何属性?
答案 0 :(得分:1)
类似的东西:
case 'SOMETHING':
const recordsCopy = {...state.records};
//change recordsCopy ...
const recordToChange = recordsCopy.find(x => x.id === '3')
if(recordToChange) {
recordToChange.name = 'new name';
}
return {...state, records: [...recordsCopy]}
答案 1 :(得分:1)
假设您有id
(第2个记录),并且想要将name
(更新为“ pqr”)
function reducer (state, action){
const {type, payload} = action
switch(type){
case: "UPDATE":
return updateRecord(state, payload.id, payload.newname)
default: return state;
}
}
function updateRecord(state, id, newName){
const newRecords = state.records.map(rec => {
if(rec.id === id){ return {...rec, name: newname} }
return rec
})
return {...state, records: newRecords}
}