表自关联时,解决列表显示顶级对象出现“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;
      }
  }
}

  

猜你喜欢

转载自www.cnblogs.com/wanbao/p/10267887.html