Javascript 是否可以在分解结构之前检查对象是否可用?

Javascript 是否可以在分解结构之前检查对象是否可用?,javascript,react-native,ecmascript-6,destructuring,Javascript,React Native,Ecmascript 6,Destructuring,我有一个要解构的值对象,但在此之前,我想检查该对象是否可用 const { contactno, contactemail } = this.props.app.user; 在这种情况下,对象用户不总是可用,因此我得到以下错误: TypeError: Cannot read property 'contactno' of undefined. 因此,在分解结构之前有没有办法检查对象是否可用?您可以这样做 const { contactno, contactemail } = (thi

我有一个要解构的值对象,但在此之前,我想检查该对象是否可用

const  { contactno, contactemail } =  this.props.app.user;
在这种情况下,对象用户不总是可用,因此我得到以下错误:

TypeError: Cannot read property 'contactno' of undefined.
因此,在分解结构之前有没有办法检查对象是否可用?

您可以这样做

const  { contactno, contactemail } =  (this.props.app && this.props.app.user) ? this.props.app.user : {} ;
你可以这样做

const  { contactno, contactemail } =  (this.props.app && this.props.app.user) ? this.props.app.user : {} ;

使用它就像下面嵌套的分解一样。如果用户未定义,则在解构中默认为{}。当用户未定义时,contactno、contactemail也未定义

const  { user: { contactno, contactemail } = {} } =  this.props.app;

使用它就像下面嵌套的分解一样。如果用户未定义,则在解构中默认为{}。当用户未定义时,contactno、contactemail也未定义

const  { user: { contactno, contactemail } = {} } =  this.props.app;

使用AND和OR操作符,您可以安全地像这样解构对象

const  { contactno, contactemail } =  (this.props.app && this.props.app.user) || {};

使用AND和OR操作符,您可以安全地像这样解构对象

const  { contactno, contactemail } =  (this.props.app && this.props.app.user) || {};

如果它是未定义的,您希望发生什么?解构往往意味着您确切地知道要传递的对象。否则,您应该将整个内容包装在ifthis.props.app.user{…}中,您可以使用if语句。或者默认为空对象this.props.app.user | |{}您可以通过以下方式尝试const{contactno,contactemail}=this.props.app&&this.props.app.user?this.props.app.user:{}@某些性能如果所需对象不可用,我不想获取任何内容,是否可以检入单个语句本身?如果未定义,您希望发生什么?解构往往意味着您确切地知道要传递的对象。否则,您应该将整个内容包装在ifthis.props.app.user{…}中,您可以使用if语句。或者默认为空对象this.props.app.user | |{}您可以通过以下方式尝试const{contactno,contactemail}=this.props.app&&this.props.app.user?this.props.app.user:{}@确定性能如果所需对象不可用,我不想获取任何内容,是否可以检入单个语句本身?