Immutable JS compare nested structures

前端 未结 3 1581
南旧
南旧 2021-01-04 07:39

I have 2 nested structures newState and newState1.

But when I compare their, equals() or Immutable.is() returned false

3条回答
  •  时光取名叫无心
    2021-01-04 07:55

    It seems that immutablejs don't do deep conversion, so if your value is object, it stays to be object.

    As you're creating different object in each update step, and those objects will be treat different when you compare to each other, so you should also convert it to Immutable.Map object, to make the compare be true.

    // Primitives.
    var test1 = Immutable.Map({
        a: 'a', 
        b: 'b', 
        c: 'c'
    });
    var test2 = Immutable.Map({
        a: 'a',
        b: 'b',
        c: 'c'
    });
    console.log('Test primitive', test1.equals(test2)); // true
    
    // Object
    test1 = Immutable.Map({
        a: 'a',
        b: 'b',
        c: {}
    });
    test2 = Immutable.Map({
        a: 'a',
        b: 'b',
        c: {}
    });
    console.log('Test object', test1.equals(test2));  // false
    // Its because
    var a = {};
    var b = {};
    console.log('a === b?', a === b); // false
    
    // Convert
    test1 = Immutable.Map({
        a: 'a',
        b: 'b',
        c: Immutable.Map({})
    });
    test2 = Immutable.Map({
        a: 'a',
        b: 'b',
        c: Immutable.Map({})
    });
    console.log('Test converted', test1.equals(test2)); // true

提交回复
热议问题