What does { …obj1, obj2 } do exactly [duplicate]

心已入冬 提交于 2019-12-13 12:43:01

问题


Let's say we have two objects:

const state = {
  fishes: { /* some obj data */ },
  animals: { /* some obj data  */ }

const animals = { /* some NEW data */ }

In Vuex there is a method replaceState(), which according to the documentation takes one argument and replaces the state with that object.

What will be the result of the following:

replaceState({ ...state, animals })

More specifically, what does { ...state, animals } do exactly?

To bring some context, I took this example from the answer of this question. In that question, the user wanted to replace the animals property of the state with the new object animals.

I'm not sure if this is relevant to Vuex / Vue.js, or is it a pure JS question, but I'll tag it with vue.js anyway.


回答1:


This is actually from ECMAScript 2018's spread syntax and ECMAScript 2015's object destructuring.

{ ...state, animals } creates a shallow copy of the state object, with a new property called animals (with the value of animals object within it).

Since you are a Vuex user, this conforms to the rule of immutable update patterns, which is to prevent the 'original' state object from being altered or mutated. You should read up on the ways of handling common operations such as add/update/delete, using the immutable pattern.




回答2:


It means Object.assign({}, state, { animals: animals} }.




回答3:


What is does is it spreads all the properties of state into the new object - making a shallow copy. All the properties in the original object (state) will be copied into the new object (the one you're passing into replaceState). Here's a simple demonstration:

let obj1 = { obj: "1" };
let obj2 = { ...obj1, obj2: true };
console.log(obj1);
console.log(obj2);

The animals bit is ES6 property shorthand, and will essentially do this:

animals: animals

It's just cleaner syntax.



来源:https://stackoverflow.com/questions/55685270/what-does-obj1-obj2-do-exactly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!