简体   繁体   English

将 If/Else 转换为三元 React Typescript

[英]Converting If/Else into Ternary React Typescript

I have a project in React and Typescript and am creating a Like button and created an if/else statement as so:我在 React 和 Typescript 中有一个项目,正在创建一个 Like 按钮并创建一个 if/else 语句,如下所示:

  const [count, setCount] = useState(0);
  const [iconFill, setFill] = useState('gray');

  const favoriteCount = () => {
    if(iconFill == 'red') {
      setCount(count - 1 );
      setFill('gray');
    } 
    else {
      setCount(count + 1);
      setFill('red');
    }
  }

The code works as expected but I am wondering if there is a more concise way to write it, I tried using a ternary statement:该代码按预期工作,但我想知道是否有更简洁的编写方式,我尝试使用三元语句:

iconFill == 'red' ? setCount(count - 1 ) && setFill('gray') : setCount(count + 1) && setFill('red');

I am unsure of why this doesn't produce the same result and am also getting the following Typescript error: An expression of type 'void' cannot be tested for truthiness我不确定为什么这不会产生相同的结果,并且还收到以下 Typescript 错误: An expression of type 'void' cannot be tested for truthiness

I think your original existing code is fine - using the conditional operator not only makes it a lot harder to read, but it also just isn't appropriate because the conditional operator is meant to be used when you want to conditionally produce an expression (but the resulting expression here isn't being used).我认为您的原始现有代码很好 - 使用条件运算符不仅会使阅读变得更加困难,而且也不合适,因为条件运算符旨在有条件地生成表达式(但此处未使用生成的表达式)。 if/else is more appropriate. if/else更合适。

But there is an alternative that can make your code more concise.但是有一种替代方法可以使您的代码更加简洁。 Because it looks like iconFill toggles between gray and red, how about making that state a boolean instead of a string?因为它看起来像iconFill在灰色和红色之间切换,那么如何将该状态iconFill布尔值而不是字符串呢? Then you can just invert the boolean:然后你可以反转布尔值:

const [fillGray, setFillGray] = useState(true);
const favoriteCount = () => {
    setCount(count + (fillGray ? 1 : -1));
    setFillGray(!fillGray);
}

The conditional operator is used above, but it's in a more appropriate context because the result is used as an expression (that is, to evaluate to 1 or -1 ) rather than as an inappropriate replacement for if/else.上面使用了条件运算符,但它在更合适的上下文中使用因为结果用作表达式(即计算结果为1-1 )而不是作为 if/else 的不适当替代。

Should you change your code?你应该改变你的代码吗? No, moving to ternary here is not an improvement, so I wouldn't.不,在这里转向三元并不是一种改进,所以我不会。

Why doesn't your proposed code work?为什么您提出的代码不起作用? In your proposed code setCount(count - 1 ) && setFill('gray') , the setFill command will only execute if setCount returns truthy .在您建议的代码setCount(count - 1 ) && setFill('gray')setFill命令仅在setCount返回truthy 时才会执行。 In all likelihood, your setter methods return undefined, so the code after && will never execute.很有可能,你的 setter 方法返回 undefined,所以&&之后的代码永远不会执行。 There is no point in evaluating B in A && B if A is false.如果 A 为假,则在A && B中评估B毫无意义。 The evaluation is short-circuited .评估是短路的

Also, minor comment, prefer === over == in JavaScript.另外,小注释,在 JavaScript 中更喜欢===不是==

Another approach can be:另一种方法可以是:

    setCount(iconFill === "red" ? count - 1 : count + 1);
    setFill(iconFill === "red" ? "gray" : "red");

Here the limitation is checking for condition twice.这里的限制是检查条件两次。

感谢大家的回应,现在对我来说很有意义,为什么三元不适合这种情况,保持我的原创!

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

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