Null合并运算符Javascript [英] Null coalescing operator Javascript

查看:65
本文介绍了Null合并运算符Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更好地处理这件事。

How to this thing in better way.

this.state.updateItem?this.state.updateItem.unit:'Unit';

我试过过this.state.updateItem.unit || 'Unit',但它发现它会产生错误,因为this.state.updateItem为NULL然后它找不到任何单位属性。

I have tried with this.state.updateItem.unit || 'Unit', but it found out that it will produce error since this.state.updateItem is NULL then it can't find any property of unit.

怎么做它以更好的方式?

How to do it in better way?

推荐答案

现在你必须这样做:

(this.state.updateItem || {}).unit || 'Unit'

对于可选链接,我们(最终希望)能够做到这样的事情:

There is a stage one proposal to ES (JavaScript) for optional chaining whereby we'll (eventually, hopefully) be able do do something like this:

this.state.updateItem?.unit || 'Unit'

如果你正在做babel,你现在可以使用它!:
https://www.npmjs.com/package/babel- plugin-transform-optional-chaining

And if you're doing babel you can use it now!:
https://www.npmjs.com/package/babel-plugin-transform-optional-chaining

这篇关于Null合并运算符Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆