1

鉴于有两种编写代码的方式,就有效代码而言,哪种方式更好?

const { match: { params: { clientId = '' } } } = this.props;

const clientId = this.props?.match?.params?.clientId ?? ''

注意我们可以忽略任何中介都可能为空的事实。我的问题更具体的是为什么每个人都默认使用对象解构,当它可以像第二种格式一样简单地编写时

4

2 回答 2

2

当然,这将是相同的,因为它们都保持引用,但想象一下如果你想从你的道具中提取多个键?

// 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默认情况下将启用该规则,并且您将被标记为使用解构赋值。

于 2020-04-14T04:44:46.077 回答
2

如果链的中间可能存在空值,您可能希望同时使用这两种技术。因为你不能有一个 null 的默认值。

const {
  clientId = '',
  clientName = ''
} = this.props?.match?.params || {};
于 2021-03-16T07:50:36.493 回答