我有一个Destructure的值对象,但在此之前,我想检查该对象是否可用,
const { contactno, contactemail } = this.props.app.user;在这种情况下,对象user并不总是可用的,因此我得到了以下错误,
TypeError: Cannot read property 'contactno' of undefined.因此,有没有办法在Destructure之前检查对象是否可用?
发布于 2020-01-09 05:19:07
使用AND和OR运算符,您可以像这样安全地构造对象。
const { contactno, contactemail } = (this.props.app && this.props.app.user) || {};发布于 2020-01-09 05:17:16
如下所示使用它(嵌套析构)。如果user是undefined,则在析构中默认为{}。当用户未定义时,contactno、contactemail也使用此方法未定义。
const { user: { contactno, contactemail } = {} } = this.props.app;发布于 2020-01-09 05:17:05
你可以这样做
const { contactno, contactemail } = (this.props.app && this.props.app.user) ? this.props.app.user : {} ;https://stackoverflow.com/questions/59657431
复制相似问题