react JavaScript 三元条件运算
react JavaScript ternary conditional operation
我从详情页导入数据json后,在ProductDetail > brand > shoes > size.length
得到长度
length 在 JSX 中输出。
但是有个问题。
详情页面的每个详细商品也有没有鞋子数据的商品。
我想把没有数据的产品当作0而不是长度当作三元运算符,但是我不知道怎么处理。
<p>{ProductDetail && ProductDetail.brand.shoes.size.length}</p>
但是在这里,没有品牌的数据使用三元运算符。
<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>
如果您需要在对象为 null 或父对象为 null 时显示 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);
我从详情页导入数据json后,在ProductDetail > brand > shoes > size.length 得到长度 length 在 JSX 中输出。
但是有个问题。 详情页面的每个详细商品也有没有鞋子数据的商品。 我想把没有数据的产品当作0而不是长度当作三元运算符,但是我不知道怎么处理。
<p>{ProductDetail && ProductDetail.brand.shoes.size.length}</p>
但是在这里,没有品牌的数据使用三元运算符。
<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>
如果您需要在对象为 null 或父对象为 null 时显示 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);