为什么我需要在此 React 方法上使用这些大括号
Why do I need to use these curly braces on this React Method
我正在将此方法添加到 React 组件中:
removeContact = (contact) => {
this.setState((currentState) => ({
contacts: currentState.contacts.filter((c) => {
return c.id !== contact.id
})
}))
每次用户按下元素的删除按钮时,该方法都会修改组件的状态,然后重新呈现页面,仅显示未删除的元素。 该方法实际上工作正常,但我不明白为什么我需要第二个花括号包含第二行箭头函数中的括号
让我标记一下我在说什么花括号
=> ({
//contacts: currentState...
}))
我知道箭头函数可以根据内容使用大括号或方括号。 但是花括号中包含括号的作用是什么?
非常感谢您的宝贵时间
"(" 使函数自动 return & "{" 是一个左对象括号
使用“(”使函数自动 return。它与
相同
=> {
return {} //contacts: currentState...
})
里面的{
只是一个普通的对象括号
所以你的 () => ({})
是一个自动 return 对象
的函数
所以基本上这意味着你在不写 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
}
}
}))
我正在将此方法添加到 React 组件中:
removeContact = (contact) => {
this.setState((currentState) => ({
contacts: currentState.contacts.filter((c) => {
return c.id !== contact.id
})
}))
每次用户按下元素的删除按钮时,该方法都会修改组件的状态,然后重新呈现页面,仅显示未删除的元素。 该方法实际上工作正常,但我不明白为什么我需要第二个花括号包含第二行箭头函数中的括号
让我标记一下我在说什么花括号
=> ({
//contacts: currentState...
}))
我知道箭头函数可以根据内容使用大括号或方括号。 但是花括号中包含括号的作用是什么?
非常感谢您的宝贵时间
"(" 使函数自动 return & "{" 是一个左对象括号
使用“(”使函数自动 return。它与
相同=> {
return {} //contacts: currentState...
})
里面的{
只是一个普通的对象括号
所以你的 () => ({})
是一个自动 return 对象
所以基本上这意味着你在不写 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
}
}
}))