Ember计算属性中如何将null值的specialty_id替换为0?
修复Ember计算属性中tspecID的null值处理问题
我一眼就发现问题出在哪了——你在idCheck函数里犯了一个拼写错误!你写的是speciality_id(少了字母c),但实际数据里的属性是specialty_id,这直接导致你的条件判断完全没按预期工作:
- 当
specialty_id是数值时,x.data.speciality_id是undefined,undefined !== null为true,所以返回x.data.specialty_id(正确的数值),看起来没问题; - 当
specialty_id是null时,x.data.speciality_id还是undefined,undefined !== null依然为true,所以还是返回x.data.specialty_id也就是null,这就是else分支永远不执行的原因。
修复后的代码
其实完全不用单独写idCheck函数,用三元表达式就能简洁解决,同时修正拼写错误:
SpecSortData: computed('customerfr', function() { let newArray = []; this.get('customerfr').forEach((x) => { const tspecID = x.data.specialty_id !== null ? x.data.specialty_id : 0; let newData = { specialtyID: x.data.specialty_id, specialty: x.data.specialty_name, customerID: x.data.customer_id, tspecID: tspecID }; newArray.push(newData); }); return newArray; }),
额外优化建议
- 用箭头函数代替普通函数,避免不必要的作用域问题;
- 如果用的是较新版本的Ember,可以用
map方法简化数组生成,同时优化计算属性的依赖,让单个元素属性变化时也能触发重计算:
SpecSortData: computed('customerfr.@each.specialty_id', function() { return this.get('customerfr').map(x => ({ specialtyID: x.data.specialty_id, specialty: x.data.specialty_name, customerID: x.data.customer_id, tspecID: x.data.specialty_id !== null ? x.data.specialty_id : 0 })); }),
内容的提问来源于stack exchange,提问作者Sorvah
相关产品推荐
相关产品推荐

