首页 > 解决方案 > 如何在 ReactNative 中检查嵌套变量的可用性而不检查所有前面的变量可用性?

问题描述

例如,在 iOS Swift 中,我可以这样做:

if (self.user?.company?.pic?.phoneNumber != null) { doSomething() }

无需:

if (self.user != null && self.user!.company != null && self.user!.company!.pic != null && self.user!.company!.pic!.phoneNumber != null) { doSomething() }

在 ReactNative(或 Javascript)中,我发现如果一个对象未​​定义,我无法检查其中是否存在变量,所以我必须先检查对象是否未定义,然后才能安全地检查其中的变量是否未定义。

if (typeof this.state.user !== "undefined" && typeof this.state.user.company !== "undefined" && typeof this.state.user.company.pic !== "undefined" && typeof this.state.user.company.pic.phoneNumber !== undefined) { this.doSomething() }

我怎样才能把它变成:

if (typeof this.state.user.company.pic.phoneNumber !== "undefined") { this.doSomething() }

或类似的东西?

谢谢。

标签: javascriptreact-nativeoptional

解决方案


如果您不能使用仍然是一个提议但可通过babel 插件使用的可选链接,您可以使用递归实用程序函数来测试每个路径段的存在:

const pluck = (item, path) => {
  const [, part, rest] = /^([^.]+)\.*(.*)/.exec(path) || [];
  if (!part) {
    return null;
  }
  const o = (item || {})[part];
  if (o == null) {
    return null;
  }

  return rest.length ? pluck(o, rest) : o;
};

if (pluck(this.state, ‘user.company.pic.phoneNumber’)) {
  doSomething();
}

推荐阅读