简体   繁体   English

JavaScript:a = Object.assign({},a,{k:v})会变异a吗?

[英]JavaScript: Will a = Object.assign({}, a, {k: v}) mutate a?

I have a object stored as key, value pairs in a url as query params. 我有一个对象存储为键,URL中的值对作为查询参数。 The keys of that object may change, and I want to use each of the key, value pairs in that object to update the key, value pairs of a state object in a redux app. 该对象的键可能会更改,我想使用该对象中的每个键值对来更新Redux应用程序中state对象的键值对。 I need to do so in a way that doesn't mutate the state object, and am currently attempting to achieve this goal as follows: 我需要以一种不会使state对象发生变异的方式进行操作,并且目前正在尝试实现以下目标:

case 'LOAD_SEARCH_FROM_URL':
  let _state = Object.assign({}, state);
  const args = action.obj.substring(1).split('&');
  args.map((arg) => {
    const split = arg.split('=');
    _state = Object.assign({}, _state, {
      [split[0]]: JSON.parse( decodeURIComponent( split[1] ) )
    })
  })
  return _state;

This works fine in simple tests, but I wanted to make sure that this is not in fact performing any mutations. 在简单的测试中这可以正常工作,但是我想确保它实际上没有执行任何突变。 I'd be grateful for any insights others can offer on this question! 对于其他人可以在这个问题上提供的任何见解,我将不胜感激!

No, Object.assign will only mutate the target (the first argument), which in your case is a newly created empty object. 不, Object.assign仅会改变目标(第一个参数),在您的情况下,该目标是新创建的空对象。 The sources (all subsequent arguments) will not be modified. 源(所有后续参数)将不会被修改。

Be very careful, Object assign mutate object if they are deeply nested. 请非常小心,如果对象嵌套深,则对象会分配它们。 And it's written in the documentation, so you should check your data structures. 它写在文档中,因此您应该检查数据结构。

For deep cloning, we need to use other alternatives because Object.assign() copies property values. 对于深度克隆,我们需要使用其他替代方法,因为Object.assign()复制属性值。 If the source value is a reference to an object, it only copies that reference value. 如果源值是对对象的引用,则仅复制该引用值。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

If you have nested state like, { a: 0 , b: { c: 0}}, trying something like this will not be detected by redux after change: 如果您拥有{a:0,b:{c:0}}之类的嵌套状态,则更改后redux不会检测到类似这样的尝试:

const mapStateToProps = state => {
  return {
    value: state[YOUR_REDUCER_NAME].a.b
  }
}
connect(mapStateToProps)(Component)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM