[英]How to prevent object/array mutation?
I've been trying to debug weird issue and I've finally figured out why it's happening. 我一直在尝试调试奇怪的问题,我终于弄清楚它为什么会发生。 Just not sure how to prevent it (; I have this function:
只是不确定如何防止它(;我有这个功能:
getInfo(id) {
id = id || "zero";
let i = routeDefinitions.findIndex(r => Boolean(r.name.toLowerCase().match(id)));
// console.log(i) - works in plunker
// but in my app sometimes returns -1...
let current = routeDefinitions[i];
let next = routeDefinitions[i + 1] ? routeDefinitions[i + 1] : false;
let prev = routeDefinitions[i - 1] ? routeDefinitions[i - 1] : false;
return { prev, current, next };
}
..it works perfectly in this plunker , but in my app I use its return value to update app state (custom implementation of redux pattern). ..在这个plunker中完美运行 ,但在我的应用程序中,我使用其返回值来更新应用程序状态(redux模式的自定义实现)。 When I send return value through this function:
当我通过此函数发送返回值时:
private _update(_old, _new) {
let newState = Object.keys(_new)
.map(key => {
if (_old[key] === undefined) {
_old[key] = _new[key];
} else if (typeof _new[key] === "object") {
this._update(_old[key], _new[key]);
} else {
_old[key] = _new[key];
}
return _old;
})
.find(Boolean);
return Object.assign({}, newState || _old);
}
.. routeDefinitions
array is mutated and things start to break... I've tried couple of things: ..
routeDefinitions
数组是变异的,事情开始破坏......我尝试了几件事:
let current = [...routeDefinitions][i];
// and:
return Object.assign({}, { prev, current, next });
..but it didn't work. ..但它没有用。 How can I prevent mutatation of
routeDefinitions
array? 如何防止
routeDefinitions
数组的routeDefinitions
?
EDIT : I've managed to reproduce the error in this plunker 编辑 :我设法重现了这个plunker中的错误
routeDefinitions array is mutated and things start to break
routeDefinitions数组发生了变异,事情开始破裂
If your function is truly: 如果您的功能是真的:
getInfo(id) {
id = id || "zero";
let i = routeDefinitions.findIndex(r => Boolean(r.name.toLowerCase().match(id)));
// console.log(i) - works in plunker
// but in my app sometimes returns -1...
let current = routeDefinitions[i];
let next = routeDefinitions[i + 1] ? routeDefinitions[i + 1] : false;
let prev = routeDefinitions[i - 1] ? routeDefinitions[i - 1] : false;
return { prev, current, next };
}
Then routeDefinitions
is not mutated . 然后,
routeDefinitions
不会发生变异 。 Something else is mutating routeDefinitions. 其他东西正在改变routeDefinitions。
I solved this by modifying _update()
like this: 我通过像这样修改
_update()
来解决这个问题:
private _update2(_old, _new) {
let newState = {};
Object.keys(_new)
.map(key => {
if (_old[key] === undefined) {
newState[key] = _new[key];
} else if (typeof _new[key] === "object") {
newState[key] = this._update2(_old[key], _new[key]);
} else {
newState[key] = _new[key];
}
return newState;
})
.find(Boolean);
return Object.assign({}, _old, newState);
}
I use old state
just to check values, don't modify it until later when _update()
is finished. 我只使用
old state
来检查值,不要在_update()
完成后再修改它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.