简体   繁体   English

有没有办法用 Javascript 解构压缩多个条件语句?

[英]Is there a way to condense multiple conditional statements with Javascript destructuring?

I'm building a simple React app that lets the user provide three types of feedback (good, neutral, and bad).我正在构建一个简单的 React 应用程序,它可以让用户提供三种类型的反馈(好的、中立的和坏的)。 If no type of feedback exists yet, it will render the "no feedback given" message, and once any type of feedback has been given, it will show the stats for it.如果尚不存在任何类型的反馈,它将呈现“未给出反馈”消息,一旦给出任何类型的反馈,它将显示其统计信息。

I've managed to accomplish this with the existing conditional shown below, but I was wondering if I can condense the three "or" statements, perhaps through a destructuring technique我已经设法使用下面显示的现有条件来完成此操作,但我想知道是否可以通过解构技术压缩三个“或”语句

Edit for clarity: the data for the feedback values is being stored in three separate pieces of state in the parent component.为清楚起见进行编辑:反馈值的数据存储在父组件中的三个单独的状态部分中。

return (
    <>
      <h1>Statistics</h1>

      {(good > 0 || (neutral > 0) || bad > 0)? 
        <p>{feedback}</p> :
        <p>No feedback given</p>}
    </>
  );

why not just do a simple string comparison , if user has feed back set feedback to that feedback if not set it to NO_FEEDBACK为什么不做一个简单的字符串比较,如果用户有反馈设置反馈,如果没有将其设置为 NO_FEEDBACK

return (
    <>
      <h1>Statistics</h1>
      {feedback != "NO_FEEDBACK"
        ?<p>{feedback}</p>
        :<p>No feedback given</p>}
    </>
  );

I've managed to accomplish this with the existing conditional shown below, but I was wondering if I can condense the three "or" statements我已经设法使用下面显示的现有条件来完成此操作,但我想知道是否可以压缩三个“或”语句

No, not really.不,不是真的。 It's only three of them, and you don't have a list of them, so there's not much to gain.只有三个,而且你没有他们的清单,所以没有什么收获。 Your current code is quite concise already - all you can do is omit the superfluous parenthesis:您当前的代码已经非常简洁 - 您所能做的就是省略多余的括号:

<>
  <h1>Statistics</h1>

  { good > 0 || neutral > 0 || bad > 0 ? 
    <p>{feedback}</p> :
    <p>No feedback given</p>}
</>

If the values are known to only be non-negative numbers (ie only 0 or > 0 ), you can also omit the > 0 comparison and just go by the truthiness of the values:如果已知这些值只是非负数(即只有0> 0 ),您也可以省略> 0比较并仅通过值的真实性:

<>
  <h1>Statistics</h1>

  { good || neutral || bad ? 
    <p>{feedback}</p> :
    <p>No feedback given</p>}
</>

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

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