Hok*_*imo 8 javascript destructuring ecmascript-6 reactjs
销毁很酷,但是在销毁嵌套对象时我开始遇到严重的问题。我有以下代码:
const {
      credit: { amont },
    } = userProfile
这很危险,因为如果信用为空怎么办?整个应用中断了。我该如何预防?我知道一种方法是使用Typescript,但我宁愿不这样做。我开始怀疑对嵌套的破坏与使用点没有什么区别。
Est*_*ask 13
It isn't possible to solve this with deep destructuring. As another answer suggests, it's possible to use default values but they are applied only to undefined values:
const { credit: { amont } = {} } = userProfile || {};
While null values still result in error, it's necessary to do short-circuit evaluation for all objects that can potentially be nully:
const { credit } = userProfile || {};
const { amont } = credit || {};
This can be addressed with safe navigation utility function that reads the path and checks for nully values.
A renowned example is Lodash get:
const amont = _.get(userProfile, 'credit.amont');
我知道一种方法是使用打字稿,但在这里我不
仅在保证类型安全的情况下,才可以使用TypeScript解决此问题。如果userProfile来自JSON响应,则必须应用运行时类型检查来断言对象不是null。