简体   繁体   English

破坏反应道具中的嵌套 object 得到错误

[英]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 user object 未定义时的未定义名称

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 .如果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:您可以在之后添加一个快速默认值以检查未定义或 null 字符串:

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

This way it will not throw an error if 'user' is undefined, name will just be undefined also.这样,如果“用户”未定义,它将不会引发错误,名称也将未定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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