【问题标题】:Spread operator [duplicate]扩展运算符 [重复]
【发布时间】:2020-04-13 21:11:09
【问题描述】:

我有来自 youtube 教程的代码,我不知道为什么我们需要括号(注释行),如果有人可以简单地解释这段代码...谢谢

  const [{count, count2}, setCount] = useState({count: 10, count2: 20})

  return (
    <div className="App">
      <button onClick={ () => 
        setCount(
          currentState => (//can not understand
            {...currentState, count: currentState.count+1}
          )
        )}>+</button>
      <h5>Count 1: {count}</h5>
      <h5>Count2: {count2}</h5>
    </div>
  )

【问题讨论】:

    标签: javascript reactjs jsx


    【解决方案1】:

    这与展开运算符无关。

    箭头函数的=&gt; 后面可以跟:

    • 表达式
    • 一个块

    因为在 JavaScript 中,{ 可以启动一个块或对象初始化器(这取决于上下文),任何你可以放置块但想要您需要将对象初始化器添加到 () 中,以便将 { 视为表达式的开头。

    【讨论】:

    • 这个答案教会了我如何正确简洁地解释一个问题^^
    【解决方案2】:

    为什么我们需要括号

    我猜是因为没有它们(),它将无法工作,即使在编译时也会引发错误。

    setCount(
      currentState => (//can not understand
        {...currentState, count: currentState.count+1}
      )
    )
    

    setCount 是一个setState hooks。它有两种语法:

    1. setCount( newStateOfCount )(使用直接值设置状态)
    2. setCount( oldCount =&gt; newCount )(使用回调设置状态)

    而你的是第二个。使用回调返回一个对象,您有 2 个选项:

    currentState => {
      return {
        ...currentState, 
        count: currentState.count+1
      }
    } 
    

    更详细
    currentState => ({
      ...currentState, 
      count: currentState.count+1
    })
    

    所以在教程中他使用了第二种语法,因为它更简洁

    没有括号是行不通的:

    currentState => {
      ...currentState, 
      count: currentState.count+1
    }
    

    因为解析器会理解{function body 的开头,而不是an object如果没有您明确地给它(),它将无法弄清楚

    【讨论】:

    • 所以基本上 ( ) 是什么让我们说转义字符?
    • @Edy 是的,我认为大致的想法是这样的。 Some character 在某些上下文中是特殊的,因此我们需要 1 个额外的“转义字符”以使语言正确理解它(针对该上下文)
    猜你喜欢
    • 2012-03-28
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多