2

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

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

在这种情况下,对象user并不总是可用,因此我收到以下错误,

TypeError: Cannot read property 'contactno' of undefined.

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

4

3 回答 3

4

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

const  { contactno, contactemail } =  (this.props.app && this.props.app.user) || {};
于 2020-01-09T05:19:07.017 回答
3

像下面这样使用它(嵌套解构)。Ifuser是解构undefined的默认值。{}当用户未定义时,contactno、contactemail 也未定义。

const  { user: { contactno, contactemail } = {} } =  this.props.app;
于 2020-01-09T05:17:16.510 回答
1

你可以这样做

const  { contactno, contactemail } =  (this.props.app && this.props.app.user) ? this.props.app.user : {} ;
于 2020-01-09T05:17:05.330 回答