【发布时间】:2020-03-04 20:11:13
【问题描述】:
我有一个接收对象数组的要求。我必须检查接收到的对象数组是否已经存在于商店中。如果是,那么我想用旧对象更新新对象,否则我想将新元素添加到商店。
const initialState = {
....
....
UserChangedData : {
....
....
changedData: []
}
}
export default function (state = initialState, action) {
switch(action.type) {
....
....
....
case SET_USER_BUCKET_LIST_DATA:
// if there is no userChangedData this condition will run initially
if (state.UserChangedData.changedData.length === 0) {
return {
...state,
UserChangedData: {
...state.UserChangedData,
changedData: [...action.payload]
}
};
}
// check if the user item already exists update them. if user item doesn't exists then add
// item to UserChangedData's changedData array with existing data. to check if the item
// exists or not we can use id.
// the object which I receive will be an array of object(s)
// scenario 1 Initial data.
// [{id:1 , name: "john", gender: "Male"}, {id:2 , name: "peter", gender: "Male"}, {id:3 ,
// name: "Natalie", gender: "Female"}, {id:4 , name: "Nicole", gender:"Female"}]
// scenario 2 : user edited one object with id 1 so update the whole object where the inital
// changedData
// example data : [{id:1 , name: "Logan", gender: "Male"}]
// scenario 3: user edited id: 1 and added a new object with id: 8 so update previous id: 1
// with new id: 1 object data and also add new object id: 8 data to changedData array.
// id: 8
// example data: [{id:1 , name: "Jane", gender: "Female"}, {id:8 , name: "Jane",
// gender:"Female"}
我尝试了很多逻辑,但都没有奏效,谁能建议我上述场景的逻辑。
【问题讨论】:
标签: reactjs redux react-redux