首页 > 解决方案 > 在解构括号内赋值?

问题描述

我熟悉解构的概念...又名:

const { name } = student // assigns a variable named name with the value of student.name

但是,今天当我看到解构中的赋值是什么时,我感到很困惑?又名:

constructor(props) {
    super(props);

    const {tabs = [{name : null}]} = props;

    const firstTab = tabs[0];

    this.state = {
        currentTab : firstTab.name
    } ;
}

这部分没看懂const { tabs = [{name : null}] } = props,有人可以帮助解释这种语法吗?

标签: javascriptreactjsecmascript-6

解决方案


[ { name: null } ]props没有属性时,这只是将选项卡的默认值设置为的一种奇特方式tabs

例子:

// When props.tabs === undefiend
let props = { param1: "param1" };
let { tabs = [{ name : null }] } = props;
console.log(tabs); // returns [{ name: null }]

// when props.tabs !== undefined
let props = { tabs: [{name: "param2"}, {name: "param3"}] };
let { tabs = [{ name : null }]} = props;
console.log(tabs) // returns [{name: "param2"}, {name: "param3"}]

这个默认值赋值的好处是它减少了错误代码。当下一行代码运行const firstTab = tabs[0]; tabs[0]时,如果您没有设置默认分配,例如会爆炸。


推荐阅读