如何定义updater
在newState.c.x === 8
中变为真,并避免state
中的任何变异?
var state = {
a: {x: 1, y: 1},
b: {x: 2, y: 2},
c: {x: 3, y: 3},
d: {x: 4, y: 4},
};
var key = 'c';
var x = 8;
var updater = {
//Having state, key and x here....
}
var newState = Object.assign({}, state, updater);
if(newState.c.x === 8) {
wooHoo();
}
提前致谢!
答案 0 :(得分:2)
您可以使用一些ES6解构和Object.assign()
。
var state = {
a: {x: 1, y: 1},
b: {x: 2, y: 2},
c: {x: 3, y: 3},
d: {x: 4, y: 4},
};
var key = 'c';
var x = 8;
var updater = {
[key]: Object.assign({}, state[key], {x})
}
var newState = Object.assign({}, state, updater);
if(newState.c.x === 8) {
alert('True')
}