Immutable of immutable data

Before talking about Immutable Data, let me talk about Mutable Data. The data created in native js are all mutable, such as:

    var a = {qty:1}
    a.qty = 10;

Some friends may say that it can be used const, const is okay for basic data types, but it has nothing to do with reference data types.

    const a = {qty:1}
    a.qty = 10;
​
    a.qty;// 10

If the object a is assigned to other variables, it will cause new problems, such as:

     const a = {qty:1}
     const b = a;
​
    a.qty = 10;
​
    b.qty;//10

At this time, you will find that the values ​​of a and b are also changed. This is actually the way js uses reference assignment to realize data sharing. The advantage is to save memory, but the disadvantages are also obvious. A little carelessness will lead to changes. The thorny problem of A and B. In a complex project, this kind of problem is not easy to troubleshoot, and there are many hidden safety hazards.

The previous approach was to use deep copy to solve this problem. Although the problem is solved, it will cause new problems: waste of memory, and some scenarios that require frequent data updates and high performance requirements (such as: React ), deep copy is actually an unwise operation, so Imutable.jsthe emergence is to solve these development pain points.

Immutable.js It was built by Facebook engineer Lee Byron for 3 years. The reference assignment in js can save memory, but as the application becomes more complex, the change of state often becomes a nightmare. The usual practice is to copy data to avoid modification. But this has caused CPU and memory consumption, and Immutable can solve these problems well by using structure sharing .

Immutable Data: Immutable Data

Immutable Data  is data that cannot be changed once it is created. Any modification or addition or deletion of the Immutable object will return a new Immutable object. The principle of Immutable implementation is Persistent Data Structure (persistent data structure), that is, the structure sharing method for data that does not need to be changed, as shown below

<!-- ![persistent data structure](./img/immutable.js structure sharing.webp "persistent data structure") -->

Common data types

  • List: Ordered index set, similar to Array in JS.
  • Map: Unordered index set, similar to Object in JS.
  • OrderedMap: Ordered Map, sorted according to the set() of the data.
  • Set: A collection without duplicate values.
  • OrderedSet: Ordered Set, sorted according to data add.
  • Stack: An ordered collection, supports adding and deleting using unshift() and shift().
  • Record: A class used to generate Record instances. Similar to JavaScript's Object, but only accepts a specific string as the key, with a default value.
  • Seq: Sequence, but may not be supported by specific data structures.
  • Collection: It is the base class for building all data structures and cannot be built directly.

As you can see, immutable.js There are many types of data, this paper describes the more common Listand Mapcorresponds to the js arrays and objects.

Conversion between js and immutable

Through fromJS()and toJS()converting two js manner and immuatble data, such as:

    import Immutable from 'immutable';
    const goods = {name:'huawei mate30 pro',price:5998,brand:'huawei'}
​
    // js -> immutable data
    const imData = Immutable.fromJS(goods)
​
    // immutable data -> js
    imData.toJS()

However fromJS(), toJS()in-depth conversion of data will result in greater overhead. Avoid use as much as possible. Single-layer data conversion should be used Map()and List()converted directly . In addition, you can also directly JSON.stringify()convert the immutable data to json strings.

    import {Map,List} from 'immutable';
​
    const initState = Map({
        breadcrumb:List([]),
        user:Map({}),
        manageMenuStatus:false
    })

Manipulate immutable data

Get the value in immutable:get(key)/getIn(keys)

The general methods of Map and List are implemented as follows
    import {Map,List} from 'immutable';
    let state = Map({
        version:'2.0',
        user:Map({
            username:'laoxie',
            age:18,
            hobby:List(['代码','电影','唱歌'])
        }),
    })
​
    // 获取 version
    state.get('version');// 2.0
​
    // 获取username
    state.getIn(['user','username']);// laoxie
​
    // 获取hobby属性数据
    state.getIn(['user','hobby',1]) // 电影
Note: Unlike traditional js, when getIn() getting the value of a deep set of objects, you don’t need to judge whether it exists at each level. If it does not exist, it will return undefined (if it is not empty in JS, an error will be reported)
  • Add the data in the immutable:set(key,val)/setIn(keys,val)
  • Delete attributes:delete(key)/deleteIn(keys)
  • Update attributes: update(key,val=>newVal)/updateIn(keys,val=>newVal) As mentioned at the beginning, Immutable Data is immutable data. All additions, deletions and changes to immutable will not modify the original data, but return a new value, so the variable needs to be re-assigned.
    import {Map,List} from 'immutable';
    let state = Map({
        version:'2.0',
        user:Map({
            id:'123',
            username:'laoxie',
            age:18,
            hobby:List(['代码','电影','唱歌'])
        }),
    })
    state.set('version','3.0');
    state.get('version');//state不被修改,所以还是返回2.0
​
    // 正确的修改方式:修改后重新赋值
    state = state.setIn(['user','age'],20);
    state.getIn(['user','age']);//20
​
    // update,delete操作同上
  • Determine whether a certain attribute exists: has(key)/hasIn(keys) This should also be a more common method in actual development. Different operations can be performed by judging whether the attribute exists. For example, it can be judged user.idto determine whether the user is logged in
    if(state.hasIn(['user','id'])){
        // 用户已经登录
    }else{
        // 用户未登录
    }
  • To determine whether two data are equal:  is(imA,imB) in JS, whether data or object, ==or ===only two variables to determine whether the address is a reference to the same object, the object is difficult to judge whether two keys are equal, and JS different, immutable compares the hashCodesum of two objectsvalueOf
  • Data merging: merge()/mergeDeep() Another commonly used operation is merging data. In JS, we generally use it Object.assign()to achieve, but Object.assign() can only do shallow merging. For deeper data, you can use immutable mergeDeep()to achieve. Two Both methods return the combined data.
    const imA = Map({
        username:'马云',
        money:150000000000,
        info:{
            married:true,
            witticism:'我没见过钱,我对钱不感兴趣'
        }
    })
    const imB = Map({
        username:'laoxie',
        gender:'男',
        info:{
            married:false,
            age:18,
        }
    })
    const newImData = imA.merge(imB);
    console.log(newImData.toJS());
    //输出 :
    // {
    //     username:'laoxie',
    //     gender:'男',
    //     money:150000000000,
    //     info:{
    //         married:false,
    //         age:18,
    //     }
    // }

    const newImData = imA.mergeDeep(imB);
    //输出 :
    // {
    //     username:'laoxie',
    //     gender:'男',
    //     money:150000000000,
    //     info:{
    //         married:false,
    //         age:18,
    //         witticism:'我没见过钱,我对钱不感兴趣'
    //     }
    // }

Of course, there are many Immutable methods. This text only involves a basic operation. If you want to know more data types, please check the official website.

 

Guess you like

Origin blog.csdn.net/GUDUzhongliang/article/details/108580503