简体   繁体   English

反应 JavaScript 三元条件操作

[英]react JavaScript ternary conditional operation

After I import the data as json from the detail page, in ProductDetail > brand > shoes > size.length get the length length is outputting in JSX.从详细信息页面将数据导入为 json 后,在 ProductDetail > brand > shoes > size.length 中获取长度长度在 JSX 中输出。

But there is a problem.但有一个问题。 There are also products without shoes data for each detailed product on the detail page.详情页也有每款详细商品没有鞋子数据的商品。 I want to treat products without data as 0 instead of length as a ternary operator, but I don't know how to handle it.我想将没有数据的产品视为 0 而不是长度作为三元运算符,但我不知道如何处理它。

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

But here, data without brand is used using the ternary operator.但在这里,使用三元运算符使用没有品牌的数据。 <p>0</p> : I want to display it like this. <p>0</p> :我想这样显示。

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>`.

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

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

If you need to show 0 when an object is null or parent object is null, Try some like below如果您需要在对象为空或父对象为空时显示0 ,请尝试以下操作

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

Basically with using optional chaining and ||基本上使用可选链接和|| operator, The output will be运算符,输出将是

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM