LWC中表格无法显示关联对象字段问题求助
问题描述
我有一个用于展示Name字段及关联对象Address字段的表格,其中Name字段可正常显示,但在HTML中使用{pcon.Address__r.Name}时会报错,仅使用{pcon.Address__r}时表格会显示[object object]。相关代码如下:
HTML代码
<table class="slds-table slds-table--bordered"> <thead> <tr> <th style="background-color: #151963;color: white;">Name</th> <th style="background-color: #151963;color: white;">Address</th> </tr> </thead> <tbody> <template for:each={pconfig} for:item="pcon" for:index="i"> <tr class={pcon.row} data-id={pcon.Id} data-index={i} key={pcon.Id} onclick{getquotes} > <td>{pcon.Name}</td> <td>{pcon.Address__r.Name}</td> </tr> </template> </tbody> </table> </lightning-layout-item>
JS代码
@wire(Vendor_getProduct,{ basketId: 'fef0E0000dwedjh' }) getProducts({error,data}) { if(data) { //console.log( 'Fetched Data ' + JSON.stringify( data ) ); this.pconfig = JSON.parse( JSON.stringify( data) ); console.log('products are:',data); } else if(error){ this.error=data; console.log('error is undefined'); } }
Apex类代码
public class c { @AuraEnabled(cacheable=true) public static List<Product_Configuration__c> getProduct (Id basketId) { return [select id, name, Address__r.name, from Product_Configuration__c where Product_Basket__c =:basketId]; } }
解决方案
1. 修复Apex查询语法错误
Apex查询中Address__r.name,末尾多余的逗号会导致查询解析失败,返回的数据结构异常。修改后的查询代码:
public class c { @AuraEnabled(cacheable=true) public static List<Product_Configuration__c> getProduct (Id basketId) { return [select id, name, Address__r.name from Product_Configuration__c where Product_Basket__c =:basketId]; } }
2. 处理关联对象为空的边界情况
当Product_Configuration__c没有关联的Address__r时,直接访问Address__r.Name会触发报错。在HTML中添加空值判断:
<td>{pcon.Address__r ? pcon.Address__r.Name : '无关联地址'}</td>
3. 简化JS数据处理逻辑
不需要通过JSON.parse(JSON.stringify(data))克隆数据,直接赋值即可,避免序列化/反序列化过程中可能破坏数据结构:
@wire(Vendor_getProduct,{ basketId: 'fef0E0000dwedjh' }) getProducts({error,data}) { if(data) { this.pconfig = data; console.log('products are:', data); } else if(error) { this.error = error; console.log('error:', error); // 修正错误日志输出 } }
4. 修复HTML事件绑定语法错误
原代码中onclick{getquotes}缺少等号,正确的事件绑定语法应为:
<tr class={pcon.row} data-id={pcon.Id} data-index={i} key={pcon.Id} onclick={getquotes} >
内容的提问来源于stack exchange,提问作者marshal panther
相关产品推荐
相关产品推荐

