How to check for availability for a nested variable without checking all the preceding variable availability, in ReactNative?

前端 未结 2 645
伪装坚强ぢ
伪装坚强ぢ 2021-01-27 05:20

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

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

Without the need t

2条回答
  •  爱一瞬间的悲伤
    2021-01-27 05:52

    If you can’t use optional chaining which is still a proposal but available via babel plugin you could use a recursive utility function to test for the presence of each path segment:

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

提交回复
热议问题