Javascript 是否在分解括号内赋值?
我熟悉解构的概念。。。又名:Javascript 是否在分解括号内赋值?,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我熟悉解构的概念。。。又名: 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];
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
例子:
这个默认值赋值的好处是,它可以减少错误代码。当下一行代码运行时,例如
const firstTab=tabs[0]代码>选项卡[0]
如果未设置默认分配,则会爆炸。这称为在分解结构内部分配。您正在将选项卡的默认值设置为包含一项的数组。一个对象有一个名为name
的键,它正在使用默认值进行解构:@jonrsharpe为什么不const{tabs=null}=props
?因为他们不希望默认值为null
?他们希望它是他们设置的值。因为制表符将是空的。。下面一行tabs[0]
会爆炸吗?我知道了,但是在constructor中为什么不this.state={currentTab:null}
?@AlisaTMorgan那么它应该是if(tabs)。。。否则…
-取决于是否有道具选项卡。不能说这是显著的改进,而是不同的方法。尤其是我会使用defaultProps
作为最明确的方式。
// 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"}]