简体   繁体   中英

destructing nested object in react prop got error

const {
    user: { name }
  } = props;

With the above code, I got

name of undefined when the user object is undefined

I like destructing but should it be used this way? The issue is there's no fallback to crash my react app. I rather do destruct and use ? as a fallback:

const {
    user
  } = props;

return <div>user?.name</div>

Try this instead:

const {
    user: { name = '' } = {name: ''}
  } = props;

<div>{name}</div>

In case that the property you are destructuring is not defined, You can assign "Default values" like this:

 const props = {diffUser: {name: "Peter"}}; const { user: {name} = {name: "default-value"} } = props; console.log(name);

The simpler example,

 var { message: msg = "Something went wrong" } = {}; console.log(msg);

A variable can be assigned a default, in the case that the value unpacked from the object is undefined .

You can just add a quick default value an check for undefined or null string after:

const { user: { name } = {} } = props;

This way it will not throw an error if 'user' is undefined, name will just be undefined also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM