Parsing nested Records in Immutable.js

前端 未结 2 1867
有刺的猬
有刺的猬 2021-02-01 23:01

Suppose I have the following Records defined using Immutable.js:

var Address = Immutable.Record({street: \'\', city: \'\', zip: \'\'});
var User = Immutable.Reco         


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-02-01 23:29

    You can make User subclass the Record definition and parse address in the constructor:

    import {Record} from 'immutable'
    
    const Address = Record({street: '', city: '', zip: ''});
    class User extends Record({name: '', address: new Address()}) {
      constructor({name, address} = {}) {
        super({name, address: new Address(address)})
      }
    }
    
    const user = new User({
      name: 'Andy',
      address: {
        street: 'wherever',
        city: 'Austin',
        zip: 'TX'
      }
    })
    
    console.log(user)
    console.log('user.address instanceof Address:', user.address instanceof Address)
    
    const user2 = new User({name: 'Bob'})
    
    console.log(user2)
    console.log('user2.address instanceof Address:', user2.address instanceof Address)
    

    Output:

    User { "name": "Andy", "address": Record { "street": "wherever", "city": "Austin", "zip": "TX" } }
    user.address instanceof Address: true
    User { "name": "Bob", "address": Record { "street": "", "city": "", "zip": "" } }
    user2.address instanceof Address: true
    

提交回复
热议问题