簡體   English   中英

錯誤TS2339:類型“ Readonly <{}>”上不存在屬性“ items”

[英]error TS2339: Property 'items' does not exist on type 'Readonly<{}>'

我有以下反應組件,但出現此錯誤:

錯誤TS2339:類型“ Readonly <{}>”上不存在屬性“ items”。

但是狀態具有items屬性

import Customer from "./Customer";

export interface IAbstractFactoryState {  
    items: Customer[];
  }

和組件:

import * as React from 'react';
import { IAbstractFactoryProps } from "./IAbstractFactoryProps";  
import { IAbstractFactoryState } from "./IAbstractFactoryState";  
import styles from './Abstractfactory.module.scss';
import { escape } from '@microsoft/sp-lodash-subset';
import DaoFactory from "./DaoFactory";  
import ICustomerDao from "./ICustomerDao";  
import DataSources from "./DatasourcesEnum";

export default class Abstractfactory extends React.Component<IAbstractFactoryProps, {}> {
    //Private instance of customerDao, please note it returns ICustomerDao, an Interface,
    //not a concrete type
    private customerDao: ICustomerDao;

    constructor(props: IAbstractFactoryProps, state: IAbstractFactoryState) {
      super(props);
      this.setInitialState();

      // We set the Dao depending on the selected data source
      this.setDaos(props.datasource);

      //Then we set the list of customers and note, we dont care if they come from Sharepoint
      //Rest API or anything else.
      this.state = {
        items: this.customerDao.listCustomers(),
      };
    }

    public render(): React.ReactElement<IAbstractFactoryProps> {
      return (
        <div className={ styles.abstractfactory }>
          <div className={ styles.container }>
            <div className={ styles.row }>
              <div className={ styles.column }>
                  {this.state.items.map( i => (<div>i.id</div>))}
               </div>
            </div>
          </div>
        </div>
      );
    }

    public setInitialState(): void {
      this.state = {
        items: []
      };
    }

    private setDaos(datasource: string): void {
      const data: DataSources = datasource === "Sharepoint" ? DataSources.SharepointList : DataSources.JsonData;
      this.customerDao = DaoFactory.getDAOFactory(data).getCustomerDAO();

      //Now, its transparent for us a UI developers what datasource was selected
      //this.customerDao.
    }
}

該錯誤是由於未將IAbstractFactoryState設置為AbstractFactory的狀態類型。 編譯器認為狀態將為空對象{}

export default class AbstractFactory extends Component<IAbstractFactoryProps, IAbstractFactoryState> 

此外,狀態不應通過構造函數傳遞。

constructor(props: IAbstractFactoryProps) {

對於狀態,請確保將所有接口成員設置為可選。

    export interface IAbstractFactoryState {  
        items?: Customer[];
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM