JS解构.如何处理空值或未定义的值 [英] JS destructuring. How to deal with null or undefined values
问题描述
如何在 es6 .这样的东西,在每个地方:
How to implement Nullable feature in es6? I need to support the source code of my previous co-worker, who used too much destructuring feature of es6. Something like this, every where:
dispatch(
loadImports(response.items.map(({ importRecord: { ['import']: importId } }) => importId))
)
在此示例中,可能会出现TypeError: Cannot read property 'import' of null
错误.
In this example, it's possible that I may get TypeError: Cannot read property 'import' of null
error.
我不想将整个结构重写为常规条件.或者,如果没有,如何在不重写的情况下处理它们?
I don't want to rewrite the whole destructures to regular conditions. Or if there isn't, how to deal with them, without rewriting?
UPD:
同事的预期版本: https://jsbin.com/fesewiy/edit?js,console
当前版本: https://jsbin.com/qirixil/edit?js,console
推荐答案
由于使用的是地图,因此需要为每个项目获取一些结果. 更改最少的最佳解决方案是仅使用一个级别的解构,然后对数组进行过滤以保留不虚假的值数组.
Because you are using map, you need to get some result for each item. The best solution with minimum changes will be to use only one level of destructuring and then filter the array to stay with array of values that are not falsy.
dispatch(
loadImports(response.items
.map(({ importRecord }) => importRecord && importRecord.import)
.filter(v => v)
))
这篇关于JS解构.如何处理空值或未定义的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!