【问题标题】:How does this object initialization work, for props?对于道具,这个对象初始化是如何工作的?
【发布时间】:2019-02-18 21:28:53
【问题描述】:

我找到了这段代码,想解释一下为什么初始化后需要“={}”。 我能弄清楚的是 1) const 使 'props' 对象 const (不是它的内容) 2) 'elementDimensions.width' 等字段已初始化,但对象设置为 ={},为什么需要这样做? 3)最后是'= props','props'是否可能向该对象添加字段? 谢谢。

export default (props) => {
    const {
        elementDimensions: {
            width = 0,
            height = 0
        } = {},
        isActive = false,
        isOutside = true,
        point: {
            x = 0,
            y = 0
        } = {}
    } = props;

    return (
        <div>
            {`x: ${x}`}<br />
....

【问题讨论】:

  • const 不会使 props 对象变为常量。 (对象根本不能是 const,但 props 变量也不是 const。)无论如何,你所拥有的是 destructuring

标签: javascript reactjs object initialization constants


【解决方案1】:
  1. 这是解构语法,而不是简单的变量赋值。从props 中提取的变量是consts 且不能重新赋值的变量——即名为widthheightisActiveisOutsidex 和@987654328 的变量@。 (这里没有对象初始化——props已经定义好了,作为函数的参数)

  2. = {} 需要为elementDimensions 提供默认值。没有它,如果 props.elementDimensions 未定义,widthheight 的解构将失败:

const props = {};
const {
  elementDimensions: {
    width = 0,
    height = 0
  }
} = props;
  1. = props 只是更多的解构语法。例如

    const { foo } = bar;
    

bar 对象中提取foo 属性,并将其放入名为foo 的变量中。

与上面的= bar 类似,代码中的= propsprops 对象中提取属性,并将它们放入变量名中。

【讨论】:

  • 哇,太棒了!谢谢。由于 elementDimensions 和 point 被命名,它们是否不是“props”参数的一部分(它们没有被解构),但子字段是。在这种情况下,它们不是解构所必需的吗?
  • 只要解构赋值的左侧包含&lt;prop&gt;: { &lt;somethingelse&gt; }prop 就不会被提取到变量中:相反,提取的任何变量都将取决于&lt;somethingelse&gt; 中的内容。冒号前面的内容描述了要查找以进行进一步提取的属性,但不提取该独立属性本身。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
  • 2019-01-12
  • 1970-01-01
  • 1970-01-01
  • 2013-06-27
  • 1970-01-01
  • 2020-11-20
相关资源
最近更新 更多