读取多个三元运算符条件



我遇到了以下代码:

      if (proto.hasOwnProperty(name)) {
         !(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name) : invariant(false) : undefined;
      }

你如何阅读第 2 行中的三元运算符?

正如其中一条评论所说,您可能应该将其转换为传统的 if-else 树以提高可读性/理智性。但是,它会读成这样(为了简洁起见,我没有逐字写出来,但你明白了要点):

if (!conditionOne) {
    if (conditionTwo) {
        return invariant(false, 'ReactClass...', name);   
    }
    else {
        return invariant(false);
    }
}
else {
   return undefined;
}

我认为通过将代码转换为 if-else 树来回答这个问题可能会帮助您更轻松地理解它:)

尝试格式化缩进代码以便更好地理解。

if (proto.hasOwnProperty(name)) {
    !(
        specPolicy === SpecPolicy.DEFINE_MANY //1
        ||
        specPolicy === SpecPolicy.DEFINE_MANY_MERGED //1
    ) ?
        process.env.NODE_ENV !== 'production' ? //2
            invariant(false, 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name) :
            invariant(false)//3
        : undefined;//4
}

(1)如果specPolicy既不是SpecPolicy.DEFINE_MANY也不是SpecPolicy.DEFINE_MANY_MERGED,则检查process.env.NODE_ENV是否不是"生产"。(2)如果是这样,则调用invariant(false, 'Re....,否则调用(3)invariant(false)。如果 (1) 为真,则返回 undefined (4)。

有两个三元运算符。看看这种格式化方式是否有帮助:

!(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED) ? 
    process.env.NODE_ENV !== 'production' ? 
        invariant(false, 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name) : 
        invariant(false) : 
    undefined;

您可以使用适当的缩进。最内三元组合在一起,如

condition1 ? condition2 ? value1 : value2 : value3

condition1 ? (condition2 ? value1 : value2) : value3

用你的代码;

!(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED) ? 
    process.env.NODE_ENV !== 'production' ? 
        invariant(false, 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name) :
        invariant(false) :
    undefined;

最新更新