空检查对象中的解构变量 [英] Null Check for destructured Variables in object

查看:88
本文介绍了空检查对象中的解构变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面显示的代码,用于从this.props.auction对象中破坏end_time属性

I have the code shown below for destructuring end_time property from this.props.auction object

const {auction: {auction: {end_time}}} = this.props;

但是,如果拍卖是一个空对象,则上述常量以上的问题将不确定.为了解决这个问题,我将代码更改为

But the issue here is above constant will be undefined if auction is an empty object. To fix this, I have changed the code to

if(Object.keys(this.props.auction).length) {
   var {auction: {auction: {end_time}}} = this.props;
} else {
   var {end_time} = "";
}

以上解决方案有效,但很难看,我相信绝对有更好的方法.

The above solution works but is ugly and I believe there is definitely a far better way of doing it.

按照这篇文章的答案

到目前为止,我的尝试是:

const {auction: {auction: {end_time = null}}} = this.props || {};

我以为上面的那个默认会将end_time设置为null,但是我想因为没有定义auction,所以会抛出错误.

I thought the above one will set end_time by default to null but I guess since auction is not defined it is throwing an error.

请提出一种更好的声明end_time常量的方法,该常量可以处理空的auction

Please suggest a better way of declaring the end_time constant which takes care of an empty auction

推荐答案

您不必在每次可以使用解构时都使用解构.

You don’t need to use destructuring every time you can use it.

const auction = this.props.auction.auction;
const end_time = auction === undefined ? null : auction.end_time;

这篇关于空检查对象中的解构变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆