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

匿名 (未验证) 提交于 2019-12-03 02:16:02

问题:

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

回答1:

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



回答2:

const add = ( a, b ) => ( a + b )

Is equivalent to

const add = ( a, b ) => { return a+b; }

When you use the () after your => it just automatically returns the values inside.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!