使用 ReactJS 声明函数组件时

When declaring a function component with ReactJS

所以我看到人们使用不同的方式来声明一个函数。但是,我看到了一种我不太理解的方式。示例代码如下:

type Props = { 
    name: string,
    age: number
}

const someFunction = ({
    name,
    age
}: Props) => {
   return (
    // Do something here
   )
}

所以我知道这段代码首先创建了一个具有名称和年龄的 Props 对象。我没有得到的部分是它显示 ({name, age}: Props) 的部分。我猜这是一个将状态映射到道具的参数,但我不确定。谁能解释一下吗?

叫做Destructuring Assignment。它是 ES6 语法。

存在 arrays and objects

它基本上是一种提取部分 array/object 的方法。

在执行 { name, age } = props 时,您是从通常称为 props 的对象中 提取 nameage

使用解构:

const someFunction = ({
    name,
    age
}: Props) => {
  console.log(name, age)
}

没有解构:

const someFunction = (props: Props) => {
  const name = props.name
  const age = props.age

  console.log(name, age)  
}