如何在React中用三元运算符替换if语句



我是ReactJS的初学者,在三元运算符方面遇到了麻烦。

我找不到在这段代码中使用三元运算符(?:(的更好解决方案,当我尝试时,我会收到错误或我的代码不工作(不显示类型(。

我的代码(如果有的话(一切正常:

const TypeChecker = (product) => {
if (
product.width === null &&
product.length === null &&
product.height === null
) {
} else {
return (
<div>
Dimensions: {product.width} x {product.length} x {product.height}
</div>
);
}
if (product.size === null) {
} else {
return <div>Size: {product.size} MB</div>;
}
if (product.weight === null) {
} else {
return <div>Weight: {product.weight} KG</div>;
}
};
return (
<div>
<div className="productContainer">
{products.map((product, key) => (
<div key={key} className="productCard" id="product">
<input
type="checkbox"
onChange={handleChange}
id="delete-checkbox"
value={product.id}
className="removeCardCheckbox cardItem delete-checkbox"
/>
<div className="cardItem">{product.sku}</div>
<div className="cardItem">{product.name}</div>
<div className="cardItem">{product.price} $</div>

{TypeChecker(product)} //Here show type if it no null
<div className="CardButtons">
<button
onClick={() => deleteProduct(product.id)}
className="btn btn-primary btn-sm m-2"
>
Delete
</button>
</div>
</div>
))}
</div>
</div>
);

例如,使用三元运算符的检查器之一:

product.width === null &&
product.length === null &&
product.height === null ? (
console.log("This is furniture")
) : (<div>
Dimensions: {product.width} x {product.length} x {product.height}
</div>)

在这种情况下,我收到错误Uncaught TypeError:(0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_3__.jsxDEV((…(不是函数

请帮我理解我的错误是什么:(

如果目标是将整个函数转换为三元条件表达式。。。

首先,改变你的条件。像这样的结构很奇怪,使您的代码更难修改/支持(正如您所发现的(:

if (product.size === null) {
} else {
return <div>Size: {product.size} MB</div>;
}

没有理由总是else块中放入逻辑。if块可以并且应该包含逻辑。因此,将上面的内容更改为:

if (product.size !== null) {
return <div>Size: {product.size} MB</div>;
}

对其他情况也要做同样的事情。那么您的函数本质上是三个条件return语句。它可以转化为一个带有链式条件运算符的return语句:

const TypeChecker = (product) =>
(product.width !== null || product.length !== null || product.height !== null) ?
(<div>Dimensions: {product.width} x {product.length} x {product.height}</div>) :
(product.size !== null) ?
(<div>Size: {product.size} MB</div>) :
(product.weight !== null) ?
(<div>Weight: {product.weight} KG</div>) :
null;

这是否比原始版本更可读或更容易修改/支持(当然是在颠倒条件之后(,这是一个意见问题。实际上没有必要将所有的条件代码转换为三元条件表达式。后者并不是前者的替代品。

最新更新