简体   繁体   中英

Use multiple lines javascript in React

I have this source code, in React function component

return (
  result.map(item => (
    <tr key={item.id}>
      <td>
      {new Date(item.pub_date).getFullYear()} /
      {new Date(item.pub_date).getMonth()} /
      {new Date(item.pub_date).getDate()}
      </td>
    </tr>

However in this script, it require three Date instances.

I want to shorten like this.

var date = new Date(item.pub_date)
date.getFullYear() / date.getMonth() /date.getDate()

Is it correct idea? or is it impossible to this in JSX??

You can achieve what you want with a little different way with the use of template literals and setting date variable outside of the return scope.

return (
  result.map(item => {
    const date = new Date(item.pub_date)

    return (
      <tr key={item.id}>
        <td>
        {`${date.getFullYear()} / ${date.getMonth()} / ${date.getDate()}`}
        </td>
      </tr>
    )
  })
)

You can create a seperate function for formatting date:

function getDate(dateValue){
     let date = new Date(dateValue);
     return `${date.getFullYear()} / ${date.getMonth()} / ${date.getDate()}`
    }

return (
  result.map(item => {
    return (
      <tr key={item.id}>
        <td>
        {getDate(item.pub_date)}
        </td>
      </tr>
    )
  })
)

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