我熟悉解构的概念......又名:
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
。有人可以帮忙解释一下这个语法吗?
最佳答案
当 props
没有属性 tabs
时,这只是将选项卡默认值设置为 [ { name: null } ]
的一种奇特方式
示例:
// 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]
将会崩溃。
关于javascript - 在解构括号内赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52621797/