箭头函数和括号 () 或 {} 或 ({}) 的使用 [英] Arrow functions and the use of parentheses () or {} or ({})

查看:30
本文介绍了箭头函数和括号 () 或 {} 或 ({}) 的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么在箭头函数中我们不需要将箭头函数的文字包裹在({})大括号中,而不是在这个例子中文字只是包裹在单个 () 大括号中.为什么?我曾在互联网上寻找答案,但失败了.

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

推荐答案

使用 ({}) 是为了 destructure 参数和 =>() 是一个隐式返回等价于 =>;{ return ()}( 仅用于消除对象的开头和函数体的左大括号之间的歧义,通常在具有多行返回值时使用.您可以简单地避免使用 ( 并将 NavLink 与箭头 =>

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

相当于

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

这篇关于箭头函数和括号 () 或 {} 或 ({}) 的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆