javascript - 在解构括号内赋值?
问题描述
我熟悉解构的概念...又名:
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
,有人可以帮助解释这种语法吗?
解决方案
[ { 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]
时,如果您没有设置默认分配,例如会爆炸。
推荐阅读
- c++ - 是否可以在文本文件中找到最长单词的长度,并在同一个文本文件中读取,只需 1 个 while 循环?
- flutter - VideoPlayerPlugin.java 使用或覆盖已弃用的 API
- python - 如何基于月份python保存数据
- sitecore - 搜索框输入中的 X 不清除文本
- ubuntu - Kubernetes 上的 Consul:Consul pod 正在运行但尚未准备好
- android - Google 不将数字资产链接识别为有效的域验证方法
- apache-nifi - NiFi:将文件内容存储在内存或全局变量中
- java - 将 C# 中由泛型类扩展的非泛型类转换为 Java
- c# - 构建并发布到 IIS 后,在发布命令中使用调试时,我总是看到生产构建
- vue.js - Vuex / Vue-Router - 将 auth:user id 从 vuex 存储传递到 vue-router 路由器链接参数