快應用如何避免讀取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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM