为什么常量名称需要在 ReactJS 中用大括号括起来

Why const names need to be wrapped in curly brackets in ReactJS

本文关键字:ReactJS 起来 常量 为什么      更新时间:2023-09-26
render () {
  const { params } = this.props.params
  return (
   <div>{ params.article }</div>
  )
}

为什么参数需要用大括号括起来,可能只是"const params = this.props.params">

称为解构。

而不是做

const params = this.props.params.params

您可以使用速记

const { params } = this.props.params.

查看示例

const a = {
  key: 'value',
  key2: 'value2',
}
const {key} = a //getting a.key from a and assigning it to key
console.log(key)
const { key2: newVar } = a //getting a.key2 from a and assigning it to newVar
console.log(newVar)

希望这有帮助!

const { foo } = bar.baz

const foo = bar.baz.foo

所以你真正在那里做的是将params设置为等于this.props.params.params

此外,这不是 React 的一个特性。相反,它是ES6 Javascript的一个特性。

它被称为解构赋值。您可以从对象或数组中提取数据或元素。

const { params } = this.props 
is same as
const params = this.props.params;

您也可以从数组中提取元素

const x = [1, 2, 3, 4, 5];
const [a, b] = x // [1, 2];

最后,您可以选择是否使用它。