首页 > 解决方案 > Salesforce、LWC、Lightning 应用程序生成器、无法读取属性

问题描述

我将组件创建为 Lightning Web 组件。在 VSCode 中没问题。当我在 Lightning App Builder 中添加此组件时,出现错误:“LWC 组件连接阶段出错:[无法读取未定义的属性‘字段’]”

产品.html:

<template>
  <div class="container">
      <a onclick={productClick}>
        <div class="product">{name}</div>
      </a>
      <a onclick={addToCart}>
        <div class="product">Add to cart</div>
      </a>
  </div>
</template>

产品.js:

import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';

const FIELDS = [
  'Account.Name',
  'Account.Phone'
];

export default class Product extends LightningElement {
  @api item; // public property
  item = recordId;

  @wire(getRecord, { recordId: '$recordId', fields: FIELDS })
  account;

  get name() {
    console.log('Returned value: ' + this.account.data.fields.Name.value);
    return this.account.data.fields.Name.value;
  }

  productClick() {

  }

  addToCart() {
    
  }
}

我使用 API v.51。它是根据本手册进行编程的。

标签: salesforcelwc

解决方案


HTML 尝试首先加载(以尽快向用户显示一些东西,任何东西。也许是一些占位符,也许是加载图标......)。这几乎是纯 html,你@wire还没有返回数据,所以你this.contact是未定义的。然而 HTML 调用 getter 会null.fields导致错误。

尝试将 HTML 包装在<template if:true>或在所有 getter 中编写类似的内容return this.account && this.account.data ? this.account.data.fields.Name.value : null;

请参阅https://developer.salesforce.com/forums/?id=9062I000000QwLGQA0中的最后一个答案,或者这也不错(但它的用法有点不同@wire):https ://salesforce.stackexchange.com/questions/264669/how -to-避免-错误-无法读取-未定义的属性-使用-两个-lwc-wired-propert


推荐阅读