Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 是否在分解括号内赋值?_Javascript_Reactjs_Ecmascript 6 - Fatal编程技术网

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"}]