在ReactNative中检查嵌套变量的可用性而不检查前面所有变

在ReactNative中检查嵌套变量的可用性而不检查前面所有变

本文介绍了如何在ReactNative中检查嵌套变量的可用性而不检查前面所有变量的可用性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,在iOS Swift中,我可以执行以下操作:

For example, in iOS Swift, I can do something like this:

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)中,我发现如果对象未定义,则无法检查其中是否存在变量,因此我必须首先检查对象是否未定义,仅然后我可以安全地检查其中的变量是否未定义.

In ReactNative (or Javascript), I found out that if an object is undefined, I can't check for the existence of the variable inside of it, so I have to check first whether the object is undefined or not, only then I can safely check whether the variable inside of it undefined or not.

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() }

还是类似的东西?

谢谢.

推荐答案

可选链接现在将成为ES2020的一部分,因此您可以执行以下操作:

Optional chaining will now be part of ES2020, and so you'll be able to do the following:

if (self.user?.company?.pic?.phoneNumber !== undefined) {
  doSomething(); // phoneNumber exists
}

话虽如此,它对浏览器的支持仍然非常有限.

With that being said, it still has very limited browser support.

因此,暂时,您可以创建一个函数,以从属性列表中递归地找到每个对象,如下所示:

So, for the time being, you could instead create a function which recursively finds each object from a list of properties like so:

const optional_chain = (obj, [key, ...props]) =>
  obj !== undefined && key ? optional_chain(obj[key], props) : obj;

const user = {
  company: {
    pic: {
      phoneNumber: 1
    }
  }
}

console.log(optional_chain(user, ['company', 'pic', 'phoneNumber'])); // 1
console.log(optional_chain(user, ['company', 'pic', 'phoneNumber', 'x'])); // undefined
console.log(optional_chain(user, ['company', 'picture', 'phoneNumber'])); // undefined
console.log(optional_chain(user, ['x', 'picture', 'phoneNumber'])); // undefined

在您的情况下,用法如下:

In your case, the usage would be as so:

if (optional_chain(self.user, ['company', 'pic', 'phoneNumber']) !== undefined) {
  doSomething();
}

这篇关于如何在ReactNative中检查嵌套变量的可用性而不检查前面所有变量的可用性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 17:40