我有下面显示的代码,用于从end_time
对象解构this.props.auction
属性
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
常量的方法,该常量可以处理空的auction
答案 0 :(得分:5)
您不必每次都可以使用销毁功能。
const auction = this.props.auction.auction;
const end_time = auction === undefined ? null : auction.end_time;
答案 1 :(得分:3)
您可能会使用默认值这样的解构方法:
const { auction: { auction: { end_time = null } = {} } = {} } = this.props || {};
但是由于上述语法繁琐且不自然,因此在这种情况下,我最终屈服于Ry's advice:
您不必每次都可以使用销毁功能。
我意识到这被标记为ecmascript-6,但是这个问题提供了一个很好的示例,其中使用optional chaining operator和nullish coalescing operator似乎是最自然的解决方案,至少当它们正式合并为ECMAScript 2020规范:
const end_time = this.props?.auction?.auction?.end_time ?? null;
答案 2 :(得分:1)
通过结合使用Optional chaining和Nullish Coalescing Operator,您可以仅使用一行来实现此目标,如下所示:
const end_time = props.auction?.auction?.end_time ?? '';
以下一些测试功能可用来理解该概念:
const end_time_defaultValue = 'end_time_defaultValue';
function testWithEndTime() {
const props = {
auction: {
auction: {
end_time: new Date(),
kay1: 'value1',
kay2: 'value2'
}
}
};
const end_time = props.auction?.auction?.end_time ?? end_time_defaultValue;
console.log('testWithEndTime() => ', end_time);
}
testWithEndTime();
// outputs the today date
function testWithoutEndTime() {
const props = {
auction: {
auction: {
kay1: 'value1',
kay2: 'value2'
}
}
};
const end_time = props.auction?.auction?.end_time ?? end_time_defaultValue;
console.log('testWithoutEndTime() => ', end_time);
}
testWithoutEndTime();
// outputs the end_time_defaultValue
// because the key 'end_time' does not exist
function testWithoutAuctionAuction() {
const props = {
auction: {
}
};
const end_time = props.auction?.auction?.end_time ?? end_time_defaultValue;
console.log('testWithoutAuctionAuction() => ', end_time);
}
testWithoutAuctionAuction();
// outputs the end_time_defaultValue
// because the key 'auction.auction' does not exist
function testWithoutPropsAuction() {
const props = {};;
const end_time = props.auction?.auction?.end_time ?? end_time_defaultValue;
console.log('testWithoutPropsAuction() => ', end_time);
}
testWithoutPropsAuction();
// outputs the end_time_defaultValue
// because the key 'props.auction' does not exist
请注意浏览器的兼容性
但是,如果您使用的是React
之类的框架,babel将为您完成这项工作。
答案 3 :(得分:1)
您可以通过 2 个步骤进行解构:首先解构您的道具,然后是在组件生命周期的某个时刻可能是 undefined
的必要对象。
// instead of
const {auction: {auction: {end_time}}} = this.props;
// you may do
const { auction } = this.props;
let end_time;
if(auction){
({ end_time } = auction);
}