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

为何Properties中的linkItems数组返回undefined?

问题:向WebPart Properties数组添加元素时触发Cannot read properties of undefined (reading 'value')错误

尝试向存储在WebPart properties中的数组添加元素时,出现错误提示:Cannot read properties of undefined (reading 'value'),相关代码定义如下:

类型定义文件

ILinkItemProps.ts

export interface ILinkItemProps {
  id:string;
  title:string;
  action:string;
  anchorid:string;
  trans:string;
}

export class LinksItem implements ILinkItemProps {
    constructor (
        public id: string  = null, 
        public title: string = null, 
        public action: string = null,
        public anchorid: string = null,
        public trans: string = null) { }
}

ILinksProp.ts

import {LinksItem} from './ILinkItemProps';
export interface ILinksProps {
    linkItems:Array<LinksItem>;
}

WebPart核心代码(webpart.ts)

public render(): void {
    const element: React.ReactElement<ILinksProps> = React.createElement(
      links,
      {
        linkItems: this.properties.linkItems,
        updateEditLink: (index: number) => {
            let arr = this.properties.linkItems;
            if (arr?.push) {
              arr.push(new LinksItem());
            } else {
              console.log('arr is undefined or null');
            }
        }
    }
)

请问该数组为何会返回undefined?


原因及解决方案

核心原因

SharePoint WebPart的this.properties字段不会自动初始化,WebPart首次加载时,linkItems没有被设置为空数组,初始状态就是undefined,这直接导致了报错。另外,直接修改this.properties的数组也不符合WebPart的属性更新规范,无法保证变更被持久化和触发组件重渲染。

解决步骤

  1. 初始化默认数组
    在WebPart的onInit方法中为linkItems初始化空数组,确保加载时就有合法的数组实例:
protected async onInit(): Promise<void> {
  await super.onInit();
  if (!this.properties.linkItems) {
    this.properties.linkItems = [];
  }
}
  1. 正确更新属性数组
    使用WebPart提供的setProperty方法更新数组,同时遵循React不可变数据原则,避免直接修改原数组:
updateEditLink: (index: number) => {
  const currentItems = this.properties.linkItems || [];
  const newItems = [...currentItems, new LinksItem()];
  this.context.propertyPane.setProperty('linkItems', newItems);
}
  1. 配置属性面板(可选)
    如果你的WebPart需要在属性面板中编辑链接项,需配置对应的集合字段,确保属性能被正确识别和持久化:
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
  return {
    pages: [
      {
        header: { description: '链接配置' },
        groups: [
          {
            groupName: '链接列表',
            groupFields: [
              PropertyPaneCollectionData('linkItems', {
                key: 'id',
                fields: [
                  PropertyPaneTextField('title', { label: '标题' }),
                  PropertyPaneTextField('action', { label: '操作标识' }),
                  // 其他字段配置
                ],
                label: '添加链接项'
              })
            ]
          }
        ]
      }
    ]
  };
}

通过以上处理,linkItems会在WebPart加载时被初始化为空数组,后续更新也会通过规范流程触发属性变更,彻底解决undefined的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 10:33:19