我正在尝试动态更改redux中的嵌套状态。";改变";或";data.epayload.peferenceType";是我想要更改的值。例如,它可以发出hud.vehicle.minimap
。我试着做第一件事,那就是newState[change] = data.payload.value
。但它并没有真正起作用。忽略电话和语音。稍后我将在那里添加值。任何帮助都会很感激的,谢谢!
const initialState = {
hud: {
hud_saves: {
current_hud: 1,
},
vehicle: {
minimap: true,
speedometer_fps: 15,
},
compass: {
showCompass: true,
showDirections: true,
compass_fps: 15,
},
status: {
health: { display: true, hide: 75 },
armor: { display: true, hide: 75 },
hunger: { display: true, hide: 75 },
thirst: { display: true, hide: 75 },
},
},
phone: {},
voice: {},
};
const PreferencesStore = (state = initialState, data: IShow) => {
switch (data.type) {
case "setPreference":
var newState = { ...state };
var change = data.payload.peferenceType;
return newState;
default:
return state;
}
};
您需要的是根据.
字符拆分键,然后在初始状态对象内部循环以找到路径。
关键部分是循环并保留最后一个元素,以便在循环外更新其值。
i < split.length - 1;
而非i <= split.length - 1;
const initialState = {
hud: {
hud_saves: {
current_hud: 1
},
vehicle: {
minimap: true,
speedometer_fps: 15
},
compass: {
showCompass: true,
showDirections: true,
compass_fps: 15
},
status: {
health: { display: true, hide: 75 },
armor: { display: true, hide: 75 },
hunger: { display: true, hide: 75 },
thirst: { display: true, hide: 75 }
}
},
phone: {},
voice: {}
};
function alterValue(obj, str) {
let split = str.split(".");
let obj2 = null;
for (let i = 0; i < split.length - 1; i++) {
if (obj2 == null) {
obj2 = obj[split[i]];
} else {
obj2 = obj2[split[i]];
}
}
obj2[split[split.length - 1]] = "11111111111";
console.log("INITIAL STATE VS FINAL STATE", initialState, newState);
}
let newState = JSON.parse(JSON.stringify(initialState));
alterValue(newState, "hud.vehicle.minimap");
如果它嵌套,您可以在这里使用spread运算符,例如,您想从vehicle
更新minimap
return {
...state,
hud: {
...state.hud,
vehicle : {
...state.hud.vehicle
minimap : data.payload.peferenceType
}
},
};