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

Is it possible to check if the object is available before Destructuring?

我有一个值为 Destructure 的对象,但在这样做之前我想检查该对象是否可用,

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

在这种情况下,对象 user 并非始终可用,因此我收到以下错误,

TypeError: Cannot read property 'contactno' of undefined.

因此,有没有办法在Destructure之前检查对象是否可用?

你可以这样做

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

像下面这样使用它(嵌套解构)。如果 userundefined 在解构中默认为 {}。当用户未定义时,contactno,contactemail 也未定义。

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

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

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