javascript - Redux 状态正在被 lodash 的 mergeWith 改变
问题描述
我正在使用 lodashmergeWith
将一些有效负载数据合并到我的一些 redux 状态中。但是,这样做时,我最终会直接改变状态。我不明白这是怎么发生的,因为我{...state}
用来进行合并。为什么会发生这种情况,我该怎么做才能不直接改变我的状态?您可以查看以下代码段,了解正在发生的事情的示例。谢谢!
const merger = (objectOne, objectTwo) => {
const customizer = (firstValue, secondValue) => {
return _.isArray(firstValue) ? secondValue : undefined;
};
return _.mergeWith(objectOne, objectTwo, customizer);
};
const state = {
1: {a: true, b: true, c: true},
2: {a: true, b: true, c: true},
3: {a: true, b: true, c: true},
}
const payload = {
2: {a: true, b: false, c: true},
}
console.log("Merged data:");
console.log(merger({...state}, payload));
console.log("Manipulated state:");
console.log(state);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
解决方案
您必须知道,扩展语法{ ...state }
只对您的对象进行浅拷贝。所以事实上 - 深层嵌套的属性 - 在您的特定情况下{ a: true, b: true, c: true }
,通过引用保持相同的对象。如果您希望避免状态突变错误,您应该使用cloneDeep
lodash 中的 eg 函数。
merger(_.cloneDeep(state), payload);
推荐阅读
- javascript - Javascript浏览器缓存甚至在文件名之后使用查询字符串
- assembly - 如何将以下 NASM 代码转换为 AT&T 语法以修复“无法处理 jmp 中的非绝对段”错误
- swift - 如何在 swift 中围绕 Alamofire.authenticate 方法制作登录异步函数包装器?
- python - 从 Python 中的微积分函数绘制速度和距离
- windows - Perl Windows 服务 - 只运行一次
- javascript - React Native - 通过 index.js 导入多个类时出错
- node.js - 从 Node JS 读取 Telegram 频道
- jquery - Jquery 不能在联系表 7 之外工作
- mysql - 使用 Django Rest 框架的 Mysql 多连接性能
- python - 如何将从s3下载的wav文件保存到文件中