首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么属性数组以未定义的形式返回?

为什么属性数组以未定义的形式返回?
EN

Stack Overflow用户
提问于 2022-07-28 11:01:05
回答 2查看 51关注 0票数 1

我试图将一个项推入存储在属性中的数组中,得到一个错误:无法读取未定义的属性(读取'value')

在我的道具里:

ILinkItemProps.ts

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
import {LinksItem} from './ILinkItemProps';
export interface ILinksProps {
    linkItems:Array<LinksItem>;
}

在webpart.ts里我有:-

代码语言:javascript
运行
复制
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');
            }
        }

    }
)

有人知道数组为什么没有定义吗?

EN

回答 2

Stack Overflow用户

发布于 2022-07-28 12:17:24

使用this.props而不是this.properties应该可以让您访问传递给组件的道具。下面是使用this.props重写的示例

代码语言:javascript
运行
复制
import React from 'react';

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

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

export interface ILinksProps {
  linkItems:Array<ILinkItemProps>;
}

export class MyList extends React.Component<ILinksProps> {
  render() {
    return <div>List count: {this.props.linkItems.length}</div>;
  }
}

export default class App extends React.Component {
  render() {
    return <MyList linkItems={[
      {id: '1'} as ILinkItemProps
    ]} />
  }
}
票数 0
EN

Stack Overflow用户

发布于 2022-07-29 13:18:51

好吧,我已经把这件事解决了,

代码语言:javascript
运行
复制
    if (!this.properties.linkItems?.push) {
      this.properties.linkItems=[];
    }
    this.properties.linkItems.push(new LinksItem())

它检查是否可以将其推送,如果没有将其设置为数组,则将其推入其中。我想知道它是否是一个bug,因为它在属性中设置为数组。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73151778

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档