【问题标题】:Object destructuring or optional chaining which is better code?对象解构或可选链接哪个更好?
【发布时间】:2020-07-26 18:33:42
【问题描述】:
鉴于有两种编写代码的方式,就有效代码而言,哪种方式更好?
const { match: { params: { clientId = '' } } } = this.props;
const clientId = this.props?.match?.params?.clientId ?? ''
N.B.我们可以忽略任何中介都可能为空的事实。我的问题更具体,为什么每个人都默认使用对象解构,什么时候可以简单地写成第二种格式
【问题讨论】:
标签:
javascript
ecmascript-6
object-destructuring
optional-chaining
【解决方案1】:
当然,这将是相同的,因为它们都保持引用,但想象一下,如果你想从你的 props 中提取多个键?
// first, do some kind of null check to make sure
// that props?.match?.params is defined, as you can destructure
// an undefined object.
const { match: { params: { clientId = '', clientName = '' } } } = this.props;
vs
const clientId = this.props?.match?.params?.clientId ?? ''
const clientName = this.props?.match?.params?.clientName ?? ''
第一种方法(对象解构)会更简洁。
当然,如果您在项目中设置了 eslint(带有 airbnb 配置),默认情况下将启用 prefer-destructuring 规则,并且您将被标记为使用解构赋值。
【解决方案2】:
如果链的中间可能存在空值,您可能希望同时使用这两种技术。因为你不能有一个 null 的默认值。
const {
clientId = '',
clientName = ''
} = this.props?.match?.params || {};