【问题标题】:Why do I need to use these curly braces on this React Method为什么我需要在这个 React 方法上使用这些花括号
【发布时间】:2020-05-28 10:42:32
【问题描述】:

我正在将此方法添加到 React 组件中:

    removeContact = (contact) => {
     this.setState((currentState) => ({
      contacts: currentState.contacts.filter((c) => {
        return c.id !== contact.id
      })
    }))

每次用户按下元素的删除按钮时,该方法都会修改组件的状态,然后重新渲染仅显示未删除元素的页面。 该方法实际上工作正常,但我不明白为什么我需要第二个花括号,其中包含第二行箭头函数中的括号。

让我标记一下我所说的花括号

=> ({
//contacts: currentState...
}))

我知道箭头函数可以使用大括号或方括号,具体取决于内容。 但是大括号中包含方括号的作用是什么?

非常感谢您的宝贵时间

【问题讨论】:

    标签: reactjs setstate


    【解决方案1】:

    "(" 使函数自动返回 & "{" 是一个左括号

    使用 "(" 使函数自动返回。它和这样做是一样的

    => {
     return {} //contacts: currentState...
    })
    

    里面的{只是一个普通的对象括号。

    所以你的() => ({}) 是自动返回对象的函数

    【讨论】:

    • 感谢乔的帮助!
    【解决方案2】:

    所以基本上这意味着你在不写return的情况下返回一个对象

    removeContact = (contact) => {
         this.setState((currentState) => ({
          contacts: currentState.contacts.filter((c) => {
            return c.id !== contact.id
          })
    }))
    

    这个和这个是一样的:

    removeContact = (contact) => {
         this.setState((currentState) => {
          console.log("This is a function and I'm in the scope of function now")
          return {
              contacts: currentState.contacts.filter((c) => {
              return c.id !== contact.id
            }
         }
    }))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-01
      • 2017-01-10
      • 1970-01-01
      • 2019-11-13
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多