一、错误如下图
二、错误原因
Cannot read property ‘unitCount’ of null
翻译成中文就是:不能读取 null 的 unitCount 属性。说明此时有 unitCount 这个属性的对象为 null。
对象为 null 的原因:页面首次加载时,会请求一次数据库。此时,若数据库中没有数据,会导致这个问题。(注:若数据库中有数据,则不会报错)
所以我这里遇到的错误就是:
后端传到前端的对象是 null, 而前端没有做非空判断就调用相关属性,导致报错。
三、解决办法
加 if 条件,或者,三元表达式,判断该对象是否为空,并将该对象赋值为默认值来解决。
原来的代码:
loadData(){
http.get('/user-report-template/analysis-setting').done(res => {
this.dataSource = res;
});
}
现在的代码:
loadData(){
http.get('/user-report-template/analysis-setting').done(res => {
// 这是新加的代码
res.condition1 = (res.condition1 === null) ? {attackCount: 500, suggestion: '', unitCount: 5} : res.condition1;
res.condition2 = (res.condition2 === null) ? {attackCount: 500, suggestion: ''} : res.condition2;
res.condition3 = (res.condition3 === null) ? {attackInterval: 2, suggestion: ''} : res.condition3;
this.dataSource = res;
});
}