Warm tip: This article is reproduced from stackoverflow.com, please click
reactjs

If within a map with arrow syntax

发布于 2020-04-03 23:20:49

I am trying to do an if like below:

<tbody>
  {aiData.map((row, index) => (
    if(row[3]==='trace'){
      <tr key={index}>
      <td>{Moment(row[0]).format("DD-MM-YYYY hh:mm:ss")}</td>
      <td>{row[3]}</td>
      <td>{row[2]}</td>
      <td>{row[1]}</td>
    </tr>
    }
    else if(row[3]==='trace'){
    }        
  ))}
</tbody>

It seems from the thread here it should be possible. But I get following error. I also tried returning the content.

Parsing error: unexpected token.

If i wrap in braces I get following: enter image description here

Questioner
Thomas Segato
Viewed
14
TBouder 2020-01-31 20:09

When you are doing xxx(YY) => (ZZ), it's the same as xxx(YY) => (return ZZ).

The best way to do what you want is to wrap the ZZ with {} to transform it as a function with possible instructions :

{
  aiData.map((row, index) => {
      if(row[3]==='trace') {
        return (
          <tr key={index}>
            <td>{Moment(row[0]).format("DD-MM-YYYY hh:mm:ss")}</td>
            <td>{row[3]}</td>
            <td>{row[2]}</td>
            <td>{row[1]}</td>
          </tr>
        )
      } else if(row[3]==='trace') {
        return (null)
      }        
  })
}