这是我的减速机。我想根据ID更新reducer中的数据而不重复。
任何人都可以帮助我。
这是我的代码:
export const dataReducer = (state= InitialState , action = null) => {
switch(action.type) {
case types.UPDATE_DATA:
return Object.assign({}, state, {
data: [
...(state.data.filter(item => (item.id !== action.payload.id))),
action.payload
]
default:
return state;
}
}
我想删除id:2,并希望将新数据添加到状态中。
var state = {
data: [
{id: 1, data: "Hello"}, {id: 2, data: "World"}
]
}
var payload= {id:2, data: "SO"}
var data1 = state.data.map(function(item){return (item.id == payload.id)? payload: item})
var data = {...state,
data: data1
}
console.log(data);
应该更新为,
var state = {
data: [
{id: 1, data: "Hello"}, {id: 3, data: "Value"}
]
}
答案 0 :(得分:3)
这将更新数据。如果它匹配数组中的任何对象。
export const dataReducer = (state= InitialState , action = null) => {
switch(action.type) {
case types.UPDATE_DATA:
return Object.assign({}, state, {
data: state.data.map(item => {
return item.id === action.payload.id ? action.payload : item;
}); // replace matched item and returns the array
});
default:
return state;
}
}
如果您想删除之前的数据并添加新数据,那么您可以尝试一次。
export const dataReducer = (state= InitialState , action = null) => {
switch(action.type) {
case types.UPDATE_DATA:
return Object.assign({}, state, {
data: state.data.filter(item => {
return item.id !== action.id; //delete matched data
}).concat(action.payload); //concats new data
});
default:
return state;
}
}
答案 1 :(得分:0)
您的解决方案取决于数据对象的组织方式。如果您的数据对象如下面的示例所示,那么使用扩展运算符语法和映射效果很好。
var state = {
data: [
{id: 1, data: "Hello"}, {id: 2, data: "World"}
]
}
var payload= {id:2, data: "SO"}
var data1 = state.data.map(function(item){return (item.id == payload.id)? payload: item})
var data = {...state,
data: data1
}
console.log(data);

您的代码
export const dataReducer = (state= InitialState , action = null) => {
switch(action.type) {
case types.UPDATE_DATA:
var temp = state.data.map(function(item){return (item.id == action.payload.id)? action.payload: item})
return {...state,
data: temp
}
default:
return state;
}
}