簡體   English   中英

reactjs、setState、Interface props 和 Interface state 之間的關系相對於 typescript,如何使用 setState?

[英]relation between reactjs ,setState, Interface props and Interface state with respect to typescript , how can I use setState?

我從未使用過 Typescript,試圖了解它是如何工作的

這個問題非常基本,可能很簡單,但我沒有找到任何可以幫助我解決這個問題的資源。

問題:我想設置 StationListState 中不存在但存在於 StationListProps 中的 StationDefs,我需要將其添加到 StationListState 中嗎? 或者以某種方式從 Station.ts 導入它,它會工作

當我嘗試在 componentDidMount 中設置 state 時,出現以下錯誤


'{ StationDefs: any; 類型的參數 }' 不可分配給 'StationListState | 類型的參數 ((prevState: Readonly, props: Readonly) => StationListState | Pick<...>) | 選擇<...>'。 Object 文字可能只指定已知屬性,並且類型“StationListState”中不存在“StationDefs” | ((prevState: Readonly, props: Readonly) => StationListState | Pick<...>) | 選擇<...>'.ts(2345)


我有 5 個文件如下

  1. 車站列表.tsx

 class StationListComponent extends React.Component < StationListProp, StationListState > { constructor(props: StationListProp) { super(props); this.state = { stationOnline: false, stationId: 0, appId: 0, activities: { selectedRow: [], } } } //I want to add following method to fetch data and allocate response to stationDefs componentDidMount() { //want to fetch data, which has Json objectArray with StationDefs content //how can i setState StationDef here? let data = [obj1, obj2, obj3]; this.setState({ stationDefs: data }); } render() {} }

  1. 站列表狀態

 interface ActivitiesType { selectedRow: Array < number | string >; } export interface StationListState { stationOnline: boolean; stationId: number appId: number; activities: ActivityType; }

  1. StationList道具

 //import {IStationDef} from Station.ts export interface StationListProp { stationDefs: IStationDef[]; }

  1. 站.ts

 import { IEnumInterface, IEntityObj } from 'index'; export interface IStationDef { StationVersionStatus: ICommonEnumInterface allowedUserTypes: ICommonEnumInterface; appDef? : IEntityObject; appId? : number; timestamp: string; }

  1. 索引.ts

 export interface IEnumInterface { stationVersionId: number; stationDescription? : string; stationName: string; } export interface IEntityObj { id: number; name: string; type? : ICommonEnumInterface; }

export interface StationListState {
  StationOnline: boolean;
  stationId: number
  appId: number;
  Activities: ActivityType;
}

能否將 StationOnline 改為 stationOnline,將 Activities 改為活動?

暫無
暫無

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

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