【问题标题】:react JavaScript ternary conditional operationreact JavaScript 三元条件操作
【发布时间】:2021-12-19 05:35:15
【问题描述】:

在我从详细页面导入数据为 json 后,在 ProductDetail > brand > shoes > size.length 获取长度 长度在 JSX 中输出。

但是有一个问题。 详情页面上的每个详细产品也有没有鞋子数据的产品。 我想把没有数据的产品当作0而不是长度当作三元运算符,但是不知道怎么处理。

<p>{ProductDetail && ProductDetail.brand.shoes.size.length}</p>

但在这里,使用三元运算符使用没有品牌的数据。 &lt;p&gt;0&lt;/p&gt; : 我想这样显示。

Nike Air Force ProductDetail > brand > shoes > size > length(0,1,2,3,4,5,6) <p>{length}</p>
jordan shoes ProductDetail > brand > shoes > size > length(0,1,2,3,4,5) <p>{length}</p>
adidas shoes ProductDetail > brand > x   -> Handles `<p>0</p>`.

【问题讨论】:

    标签: javascript arrays reactjs ecmascript-6


    【解决方案1】:

    你可以像这样使用三元运算符和可选链

    <p>{ProductDetail?.brand?.shoes?.size?.length ? ProductDetail.brand.shoes.size.length : null}</p>
    

    【讨论】:

    • TypeError: Cannot read properties of undefined(reading '0') Products with null data does not have brand > x.
    • ProductDetail?.brand?.shoes?.size?.length ? ProductDetail.brand.shoes.size.length : nullProductDetail?.brand?.shoes?.size?.length 基本相同。没有必要让它变得更复杂。
    【解决方案2】:

    如果您需要在对象为空或父对象为空时显示0,请尝试以下方式

    <p>{ProductDetail?.brand?.shoes?.size?.length || 0}</p>
    

    基本上使用可选链接和|| 运算符,输出将是

    ProductDetail is null/undefined ==> 0
    ProductDetail.brand null/undefined ==> 0
    ....
    ProductDetail.brand.shoes.size has valid array ==> length
    

    let ProductDetail = { brand: { shoes: { size: [2, 3] } } };
    console.log(ProductDetail?.brand?.shoes?.size.length || 0);
    
    ProductDetail = null;
    console.log(ProductDetail?.brand?.shoes?.size.length || 0);
    
    ProductDetail = { brand: { shoes: null } }
    console.log(ProductDetail?.brand?.shoes?.size.length || 0);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      • 2021-09-21
      • 2020-06-13
      • 1970-01-01
      相关资源
      最近更新 更多