快应用如何避免读取undefined变量的属性导致报错

现象描述

这是 JS 开发中常见的错误。对一个值为 null 或 undefined 的变量取属性就会报错。例如:

1
2
3
<!-- a = {}; --> 
<text>{{ a.b.c }}</text>
<!-- Error: Cannot read property 'c' of undefined -->

解决方法

1、&& 方法,通过逻辑运算的执行顺序来规避错误。代码如下:

app.ux代码如下:

1
<text>{{ a && a.b && a.b.c }}</text>

2、 在 ViewModel 上增加函数方法

推荐方案 2,在 ViewModel 上建立一个 checkEmpty 函数。示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
export default {
  checkEmpty(...args) {
    let ret
    if (args.length > 0) {
      ret = args.shift()
      let tmp
      while (ret && args.length > 0) {
        tmp = args.shift()
        ret = ret[tmp]
      }
    }
    return ret || false
  }
}

这样,就可以方便的调用了。

1
<text>{{checkEmpty(a, 'b''c')}}</text>

原文链接:https://developer.huawei.com/...
原作者:Mayism

原文地址:https://www.cnblogs.com/developer-huawei/p/15038204.html