简体   繁体   中英

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

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:

<>
  <h1>Statistics</h1>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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