1. 程式人生 > >表自關聯時,解決列表顯示頂級物件出現“Cannot read property 'xxx' of null”的問題

表自關聯時,解決列表顯示頂級物件出現“Cannot read property 'xxx' of null”的問題

當表設計中涉及自關聯時,同時在列表中顯示自關聯物件的屬性,如果自關聯物件為null,則渲染頁面時會出現Cannot read property 'xxx' of null問題

問題描述

例如下表中parent的值是test_type表的id

create table test_type

(
  id bigint not null,
  name varchar(20) not null,
  parent bigint,
  ……
  primary key (id)
);

id name parent
1 測試型別1 NULL
2 測試型別2 1

 

 

 

頁面程式碼中,用bootstrap table展示,如果此時parent為null時,頁面就會報‘Cannot read property 'name' of null’。

columns: [{
    title: "ID",
    field: "id"
  },{
    title: "父型別",
    field: "parent.name",
  }
  ……
]

 

解決方案

修改filed,去掉”.屬性“引用,改用物件,然後加入formatter,判斷物件是否為null,如果不為null,將引入其屬性。

{
  title: "父型別",
   field: "parent",
   formatter: function (value, row, index) {
     if (value == null || value == 'null') {
       return '';
     } else {
         return value.name;
      }
  }
}