JS uses destructuring assignment to update some properties of objects

introduction

Today, when I was looking at the background management project of vue3+TS, I found an interesting thing. When the framework author updates some properties of an object in the state in vuex, he uses deconstruction assignment. There are many ways to update some properties of the object. But this is relatively new, and it is shared with other methods.

The usefulness is that when encountering a very large object, most of the attributes are reused, and only a small part of the attributes are updated.

Summarize

As usual, let me summarize first.

  • destructuring assignment(...)

//需要更新的源对象
let state={
    name:'genting',
    sex:'male',
    list:[1,2,3]
}

//进行了某些操作,比如接口获取了更新数据
//需要更新的数据
let obj2={
    name:'incubus',
    age:18,//新增的数据
    list:[4,5,6]||[]//覆盖或清空
}

//...state需要在最上面,否则不能覆盖/更新
let obj1={
    //源对象
    ...state,

    //更新的数据
    /* name:'incubus',
    age:18,//新增的数据
    list:[4,5,6]||[]//覆盖或清空 */

    //或者这样写法
    ...obj2
}

state=obj1

/* 结果
    state={
        name:'incubus',//更新了
        sex:'male',//复用
        age:18,//新增了
        list:[4,5,6]//更新了
    } 
*/

  • Object method (Object.assign)

let state={
    name:'genting',
    sex:'male',
    list:[1,2,3]
}

//进行了某些操作,比如接口获取了更新数据
//需要更新的数据
let obj2={
    name:'incubus',
    age:18,
    list:[4,5,6]||[]//覆盖或清空
}

state=Object.assign(state,obj2)//注意顺序

/* 结果
state={
    name:'incubus',//更新了
    sex:'male',//复用
    age:18,//新增了
    list:[4,5,6]//更新了
} 
*/

This method can also be used to compose new objects, copy objects

  • Assign manually...

Like in vue2, if you need responsiveness, you have to manually $set(obj,key,value)

Sometimes an error will be reported for a key name that the assignment object does not have. Try to avoid this kind of operation.

important point

The principle is to use the latter to cover the former.

But the destructuring assignment is special, because direct writing cannot pass. Very interesting way of writing, if you encounter it, don’t miss it.

let obj={
    list:[],
    list:[4,5,6]||[]//报错
}

Guess you like

Origin blog.csdn.net/weixin_43818307/article/details/129203153