我正在使用Redux。在我的reducer中,我试图从这样的对象中删除一个属性:
const state = {
a: '1',
b: '2',
c: {
x: '42',
y: '43'
},
}
我想拥有这样的东西而不必改变原始状态:
const newState = {
a: '1',
b: '2',
c: {
x: '42',
},
}
我试过了:
let newState = Object.assign({}, state);
delete newState.c.y
但是由于某些原因,它会同时从两个状态中删除该属性。
能帮我做到吗?
如何使用解构赋值语法?
const original = {
foo: 'bar',
stack: 'overflow',
};
// If the name of the property to remove is constant
const { stack, ...withoutFirst } = original;
console.log(withoutFirst); // Will be { "foo": "bar" }
// If the name of the property to remove is from a variable
const key = 'stack'
const { [key]: value, ...withoutSecond } = original;
console.log(withoutSecond); // Will be { "foo": "bar" }
// To do a deep removal with property names from variables
const deep = {
foo: 'bar',
c: {
x: 1,
y: 2
}
};
const parentKey = 'c';
const childKey = 'y';
// Remove the 'c' element from original
const { [parentKey]: parentValue, ...noChild } = deep;
// Remove the 'y' from the 'c' element
const { [childKey]: removedValue, ...childWithout } = parentValue;
// Merge back together
const withoutThird = { ...noChild, [parentKey]: childWithout };
console.log(withoutThird); // Will be { "foo": "bar", "c": { "x": 1 } }
我觉得ES5阵列的方法,如filter
,map
和reduce
有用的,因为他们总是返回新的数组或对象。在这种情况下,我将Object.keys
遍历对象,然后Array#reduce
将其变回对象。
return Object.assign({}, state, {
c: Object.keys(state.c).reduce((result, key) => {
if (key !== 'y') {
result[key] = state.c[key];
}
return result;
}, {})
});
您可以_.omit(object, [paths])
从lodash库中使用
路径可以嵌套,例如: _.omit(object, ['key1.key2.key3'])
只需使用ES6对象解构功能
const state = {
c: {
x: '42',
y: '43'
},
}
const { c: { y, ...c } } = state // generates a new 'c' without 'y'
console.log({...state, c }) // put the new c on a new state
那是因为您state.c
要将的值复制到另一个对象。该值是指向另一个javascript对象的指针。因此,这两个指针都指向同一对象。
试试这个:
let newState = Object.assign({}, state);
console.log(newState == state); // false
console.log(newState.c == state.c); // true
newState.c = Object.assign({}, state.c);
console.log(newState.c == state.c); // now it is false
delete newState.c.y;
您还可以对对象进行深度复制。看到这个问题,您会发现最适合您的。
这个怎么样:
function removeByKey (myObj, deleteKey) {
return Object.keys(myObj)
.filter(key => key !== deleteKey)
.reduce((result, current) => {
result[current] = myObj[current];
return result;
}, {});
}
它过滤应删除的键,然后从其余键和初始对象中构建一个新对象。泰勒·麦金尼斯(Tyler McGinnes)出色的reactjs程序盗用了这个想法。
function dissoc(key, obj) {
let copy = Object.assign({}, obj)
delete copy[key]
return copy
}
另外,如果要寻找功能性的编程工具包,请查看Ramda。
在您的情况下,可以使用不可变性助手来取消设置属性:
import update from 'immutability-helper';
const updatedState = update(state, {
c: {
$unset: ['y']
}
});
从2019年开始,另一种选择是使用该Object.fromEntries
方法。已经到了阶段4。
const newC = Object.fromEntries(
Object.entries(state.c).filter(([key]) => key != 'y')
)
const newState = {...state, c: newC}
关于它的好处是它可以很好地处理整数键。
使用Immutable.js很容易:
const newState = state.deleteIn(['c', 'y']);
您遇到的问题是您没有深入克隆初始状态。所以你有一个浅表副本。
您可以使用传播算子
const newState = { ...state, c: { ...state.c } };
delete newState.c.y
或遵循相同的代码
let newState = Object.assign({}, state, { c: Object.assign({}, state.c) });
delete newState.c.y
我通常使用
Object.assign({}, existingState, {propToRemove: undefined})
我意识到这实际上并没有删除该属性,但几乎在所有目的上1都在功能上等效。它的语法比我认为是相当不错的折衷的替代方法要简单得多。
1如果使用hasOwnProperty()
,则需要使用更复杂的解决方案。
我用这个模式
const newState = Object.assign({}, state);
delete newState.show;
return newState;
但在书中我看到了另一种模式
return Object.assign({}, state, { name: undefined } )
效用 ;))
const removeObjectField = (obj, field) => {
// delete filter[selectName]; -> this mutates.
const { [field]: remove, ...rest } = obj;
return rest;
}
动作类型
const MY_Y_REMOVE = 'MY_Y_REMOVE';
动作创造者
const myYRemoveAction = (c, y) => {
const result = removeObjectField(c, y);
return dispatch =>
dispatch({
type: MY_Y_REMOVE,
payload: result
})
}
减速器
export default (state ={}, action) => {
switch (action.type) {
case myActions.MY_Y_REMOVE || :
return { ...state, c: action.payload };
default:
return state;
}
};
正如一些答案中所暗示的,这是因为您正在尝试修改嵌套状态,即。更深一层。一个规范的解决方案是在x
状态级别添加一个reducer :
const state = {
a: '1',
b: '2',
c: {
x: '42',
y: '43'
},
}
深层减压器
let newDeepState = Object.assign({}, state.c);
delete newDeepState.y;
原装液位降低器
let newState = Object.assign({}, state, {c: newDeepState});
文章标签:immutability , javascript , redux
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!