我有下面所示的代码,用于从 this.props.auction
对象解构 end_time
属性
const {auction: {auction: {end_time}}} = this.props;
但是这里的问题是,如果拍卖是一个空对象,上面的常量将是未定义的。为了解决这个问题,我将代码更改为
if(Object.keys(this.props.auction).length) {
var {auction: {auction: {end_time}}} = this.props;
} else {
var {end_time} = "";
}
上述解决方案有效,但很丑陋,我相信肯定有更好的方法。
遵循this post的答案和
到目前为止我的尝试是:
const {auction: {auction: {end_time = null}}} = this.props || {};
我认为上面的方法会将 end_time
默认设置为 null
但我猜由于 auction
未定义,因此会引发错误。
请建议一种更好的方法来声明 end_time
常量,该常量负责空的拍卖
最佳答案
您不需要在每次可以使用解构时都使用它。
const auction = this.props.auction.auction;
const end_time = auction === undefined ? null : auction.end_time;
关于javascript - 空检查对象中的解构变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59259682/