[英]destructuring multiple times for the same object property
Sometimes I do nested destructing, meaning more than a level, it can be dangerous but I only ensure the property exist otherwise I'll have the property of undefined error . 有时我做嵌套破坏,意味着不仅仅是一个级别,它可能是危险的,但我只确保属性存在,否则我将具有未定义错误的属性。
I did this recently, 我最近做了这个,
const {
match: {
params: { id: UserId }
},
match
} = this.props
and I have doubt whether is good code. 我怀疑是否是好的代码。 I need
match.params.id
, and I also need the match
object, so this duplicated 'variable' is fine? 我需要
match.params.id
,我还需要match
对象,所以这个重复的'变量'是好的吗?
no do it like this: 不这样做:
const {match} = this.props;
const {params: {id: userId} = {} } = match || {};
Like @Tarek said, that is the better way to do it. 就像@Tarek说的那样,这是更好的方法。 Just to check that the object and its properties are indeed valid.
只是为了检查对象及其属性是否确实有效。
This is also a good opportunity to check out the optional chaining operator! 这也是检查可选链接操作符的好机会! It is an experimental babel plugin that will (hopefully) be added to ES9!
这是一个实验性的babel插件,有望(希望)添加到ES9!
This is doing exactly what you would want in a much cleaner and simpler way. 这正是以更清洁,更简单的方式完成您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.