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.
Cannot read property 'Name' of undefined
shops
How can I make sure that nested objects within are shopsset to the correct default value, even if defined shops?
, . , . shops.
, cakeShop pieShop .
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}; }
,
function mapStateToProps({ shops: { cakeShop = {}, pieShop = {} } = {} } = {}) { ... }
, , , , , lodash underscore:
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 } }
Source: https://habr.com/ru/post/1672559/More articles:moving array elements inside an array - arraysEF Core DeleteBehavior.SetNull causes cyclic problems - .net-coreCan I change the certificate of the Android application in the play store - androidRunge-Kutta code does not match the built-in method - systemError in RK4 algorithm in Python - pythonHow to transfer a solid differential equation through Runge-Kutta 4 - c #Get version information for Firebird server - javaHow do I target the first and last item in a grid row of dynamic records? - javascriptImplement pseudo-spectral method with RK4 in Python - pythonCan I use asynchronous timer in PHP and how to do it? - phpAll Articles