空检查对象中的解构变量

问题描述:

我有下面显示的代码,用于从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;