给出两种编写代码的方法,哪种方法对有效代码更好?
ansible.cfg
const { match: { params: { clientId = '' } } } = this.props;
< br />
NB我们可以忽略任何中介都可以为空的事实。我的问题更具体,原因是为什么每个人都可以默认将对象分解作为默认形式,而对象构造可以简单地以第二种格式编写
答案 0 :(得分:1)
当然,它们都是相同的,都是一样的,但是想像一下是否要从道具中提取多个键?
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
规则,并且将标记您使用解构分配。
答案 1 :(得分:1)
如果链中间可能存在空值,您可能希望同时使用这两种技术。因为你不能有一个 null 的默认值。
const {
clientId = '',
clientName = ''
} = this.props?.match?.params || {};