Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

javascript - Arrow functions and the use of parentheses () or {} or ({})

I cannot understand why in the arrow functions we do not need to wrap the literal of arrow function in the ({}) braces, instead of in this example the literal just wrapped in the single () braces. Why? I had surfed the internet to find an answer on it, but it failed.

And also why we put the arguments in double braces ({}), instead of just ()?

const FilterLink = ({ filter, children }) => (
   <NavLink
       to={filter === 'SHOW_ALL' ? '/' : `/${ filter }`}
       activeStyle={ {
       textDecoration: 'none',
           color: 'black'
       }}
   >
       {children}
   </NavLink>
)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using ({}) is to destructure the arguments and => () is an implicit return equivalent to => { return ()} and ( only serves to disambiguate between the start of an object and the opening braces of a function body and would generally be used when you have a multiline return value. You could simply avoid using ( and have the NavLink in the same line as the arrow =>

const FilterLink = ({ filter, children }) => ( // <-- implicit return 
  <NavLink
    to={filter === 'SHOW_ALL' ? '/' : `/${ filter }`}
    activeStyle={ {
      textDecoration: 'none',
      color: 'black'
    }}
  >
    {children}
  </NavLink>
)

is equivalent to

const FilterLink = ({ filter, children }) => {
   return (
      <NavLink
        to={filter === 'SHOW_ALL' ? '/' : `/${ filter }`}
        activeStyle={ {
          textDecoration: 'none',
          color: 'black'
        }}
      >
        {children}
      </NavLink>
    )
}

Check this answer for more details on the usage of destructuring in ({ filter, children })


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...