You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LWC调用Apex查询账户关联联系人后lightning-datatable不显示数据如何解决

问题排查与修复方案

核心问题点

  • Apex方法返回类型错误:当前声明返回单个Contact对象,但Database.query查询满足条件的所有联系人时返回的是List<Contact>集合,当查询结果大于1条时会直接抛出类型转换异常,导致返回错误。
  • LWC Wire传参写法错误:Wire装饰器的参数如果要引用组件实例的属性,不能直接使用this,需要用$前缀标记响应式参数,否则解析时AccountId为undefined,Apex无法收到正确的过滤条件。
  • 未声明AccountId为API暴露属性:如果通过父组件/自定义标签传递账户ID,需要给AccountId添加@api装饰器才能接收外部传入的值。
  • datatable的key-field大小写错误:Salesforce标准记录ID字段为大写Id,HTML中写小写id会导致组件无法正确识别行唯一标识,可能出现渲染异常。

修正后代码

Apex代码

@AuraEnabled(cacheable = true)
public static List<Contact> GetContacts(String AccountId){
        String query = 'SELECT Name,Phone,Email FROM Contact WHERE AccountId =: AccountId';
        return Database.query( query );
}

JS代码

import { LightningElement, api, wire, track } from 'lwc';
// 请把下方的「你的Apex类名」替换为你实际的Apex类名称
import GetContacts from '@salesforce/apex/你的Apex类名.GetContacts';

const columns = [    
    { label: "Name", fieldName: "Name" },   
    { label: "Phone", fieldName: "Phone"},
    { label: "Email", fieldName: "Email"}
];

// 请把下方的「你的组件名」替换为你实际的LWC组件名称
export default class 你的组件名 extends LightningElement {
    @api AccountId; 
    @track contactsList =[];
    error;

    @wire(GetContacts,{AccountId:'$AccountId'}) 
    WireContactRecords({error, data}){
        console.log('Entering WireContactRecords');
        console.log('传入的AccountId===='+this.AccountId);
        if(data){
            console.log('查询到的联系人数据*********'+JSON.stringify(data))
            this.contactsList = data;
            this.error = undefined;
        }else{
            this.error = error;
            this.contactsList = undefined;
        }
    }
}

HTML代码

<lightning-datatable
    data={contactsList}
    columns={columns}
    key-field="Id"
    hide-checkbox-column>
</lightning-datatable>

内容的提问来源于stack exchange,提问作者user97539

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 02:39:03