我有一个对象在Redux中进行突变之前尝试过深地克隆它,但是嵌套对象在用lodash或json进行深克隆之后变成空的
const initial = {
infamy: {a: 1}
}
export const playerReducer = (state = initial, action) => {
switch (action.type) {
case SET_DATA:
console.log("III", state);
state = cloneDeep(state); //Why the neseted obj becomes empty?
console.log("JJJ", state);
break;
}
};
编辑: 看起来问题出在我检查对象是否为空的条件不起作用,所以api中的空数据代替了初始值,但使console.log为何显示后发突变而不是先发突变突变
case SET_DATA:
console.log("III", state);
const nextState = cloneDeep(state);
console.log("JJJ", nextState); //why the log shows the change in line 10 made? shouldn't it log the values then change happen?
nextState.membershipId = action.payload.membershipId;
nextState.membershipType = action.payload.membershipType;
nextState.displayName = action.payload.displayName;
console.log(action.payload.gambitStats);
if (action.payload.gambitStats.allTime !== "undefined") { //the bug is here
nextState.gambitStats = cloneDeep(action.payload.gambitStats);
nextState.infamy = cloneDeep(action.payload.infamy);
}
return nextState;
答案 0 :(得分:0)
原则上,我想说,state
不会被单独使用cloneDeep
清空。
另一方面,我看到您正在使用Redux模式,并且您不应该直接操纵状态。
相反,您应该返回下一个状态,并且默认情况下还应返回当前状态。
const initial = {
infamy: {a: 1}
}
export const playerReducer = (state = initial, action) => {
switch (action.type) {
case SET_DATA:
const nextState = cloneDeep(state);
// Modify nextState according to the intent of your action
return nextState;
default:
return state;
}
};
希望有帮助。 :)
答案 1 :(得分:0)
您正在检查undefined
是否为字符串"undefined"
,而不是:
if (action.payload.gambitStats.allTime !== undefined) { ...
或者只是:
if (!!action.payload.gambitStats.allTime)