gpt4 book ai didi

javascript - 如何防止对象/数组突变?

转载 作者:太空狗 更新时间:2023-10-29 17:41:02 26 4
gpt4 key购买 nike

我一直在尝试调试奇怪的问题,我终于弄清楚了为什么会这样。只是不确定如何防止它(;我有这个功能:

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 };
}

..它在 this plunker 中完美运行,但在我的应用程序中,我使用它的返回值来更新应用程序状态(redux 模式的自定义实现)。当我通过这个函数发送返回值时:

  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 数组发生了变化,事情开始崩溃......我已经尝试了几件事:

let current = [...routeDefinitions][i];
// and:
return Object.assign({}, { prev, current, next });

..但它没有用。如何防止 routeDefinitions 数组发生突变?

编辑:我成功重现了 this plunker 中的错误

最佳答案

routeDefinitions array is mutated and things start to break

如果你的函数是真的:

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 };
}

然后 routeDefinitions 不发生变化。其他东西正在改变 routeDefinitions。

关于javascript - 如何防止对象/数组突变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34840334/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com