[英]Are these codes immutable?
I have to change state in my component, but I don't know whether this code is immutable. 我必须在我的组件中更改状态,但我不知道此代码是否是不可变的。 I came up with two ways to solve this problem. 我提出了两种解决这个问题的方法。 Both of these codes work well but don't know if they are immutable. 这两个代码都运行良好但不知道它们是否是不可变的。 I would be grateful if you could tell me which is better or which is better than these codes. 如果你能告诉我哪个更好或哪个比这些代码更好,我将不胜感激。
Trial 1 试验1
handleRemove = id => {
const { dummyData } = this.state;
delete dummyData[id];
this.setState({ dummyData });
};
Trial 2 试用2
handleRemove = id => {
const { dummyData } = this.state;
this.setState({
dummyData: {
...Object.keys(dummyData)
.filter(key => key !== id)
.reduce((acc, cur) => {
return {
...acc,
[cur]: dummyData[cur]
};
}, {})
}
});
};
Trial 1 will mutate dummyData
, trial 2 will not, but it's overly complicated. 试验1将改变dummyData
,试验2不会,但它过于复杂。
Other alternative are: 其他替代方案是:
use es6 object destructuring: 使用es6对象解构:
const { [id]: _, ...dummyData } = this.state.dummyData; this.setState({ dummyData });
use other utility function like lodash's _.omit
使用其他实用功能,如lodash的_.omit
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.