ES6 Object Destructuring Default Values ​​for Nested Parameters

I am using destructuring an es6 object to provide default parameters for a function.

function mapStateToProps({ shops: { cakeShop: {}, pieShop: {} }) {
  return {
    CakeShopName: shops.cakeShop.Name,
    PieShopName: shops.pieShop.Name
  }
}

The problem with the above is that if I call

mapStateToProps({})

The code throws Cannot read property 'Name' of undefined. Nested objects in shopsdo not have default values, and the code has a null reference.

How can I make sure that nested objects within are shopsset to the correct default value, even if defined shops?

+4
source share
3 answers

, . , . shops.

, cakeShop pieShop .

function mapStateToProps({ shops: { cakeShop = {}, pieShop = {} }) {
// short for             { shops: { cakeShop: cakeShop = {}, pieShop: pieShop = {} }) {
// parameter names (that will be bound):      ^^^^^^^^                ^^^^^^^
  return {
    CakeShopName: cakeShop.Name,
    PieShopName: pieShop.Name
  }
}

function mapStateToProps({ shops: { cakeShop: {name: CakeShopName} = {}, pieShop: {name: PieShopName} = {} }) {
  return {CakeShopName, PieShopName};
}
+6

,

function mapStateToProps({ shops: { cakeShop = {}, pieShop = {} } = {} } = {}) {
...
}
+5

, , , , , lodash underscore:

function mapStateToProps(shops) {
  _.defaultsDeep(shops, {
    cakeShop: {
      Name: "Kiki CakeShop"
    }, 
    pieShop: {}
  })

  return {
    CakeShopName: shops.cakeShop.Name, // defaults to "Kiki CakeShop"
    PieShopName: shops.pieShop.Name // undefined if not specified
  }
}
0

Source: https://habr.com/ru/post/1672559/


All Articles