【问题标题】:relation between reactjs ,setState, Interface props and Interface state with respect to typescript , how can I use setState?reactjs ,setState,Interface props 和 Interface state 之间关于 typescript 的关系,我该如何使用 setState?
【发布时间】:2020-11-18 21:52:09
【问题描述】:

我从未使用过 Typescript,试图了解它是如何工作的

这个问题非常基本,可能很简单,但我没有找到任何可以帮助我解决这个问题的资源。

问题:我想对 StationListState 中不存在但在 StationListProps 中存在的 StationDefs 设置状态,我需要将其添加到 StationListState 中吗?或以某种方式从 Station.ts 导入它,它会工作

当我尝试在 componentDidMount 中设置状态时,出现以下错误


类型参数 '{ StationDefs: any; }' 不可分配给 'StationListState | 类型的参数((上一个状态: 只读,道具:只读)=> 站列表状态 |选择<...>) |选择<...>'。对象字面量只能 指定已知属性,并且类型中不存在“StationDefs” '站列表状态 | (((prevState:只读,道具: 只读) => StationListState |选择<...>) | 选择<...>'.ts(2345)


我有 5 个文件如下

  1. StationList.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. StationListState

interface ActivitiesType {
  selectedRow: Array < number | string > ;
}

export interface StationListState {
  stationOnline: boolean;
  stationId: number
  appId: number;
  activities: ActivityType;
}
  1. StationListProps

//import {IStationDef} from Station.ts

export interface StationListProp {
  stationDefs: IStationDef[];
}
  1. Station.ts

import {
  IEnumInterface,
  IEntityObj
} from 'index';

export interface IStationDef {
  StationVersionStatus: ICommonEnumInterface
  allowedUserTypes: ICommonEnumInterface;
  appDef ? : IEntityObject;
  appId ? : number;
  timestamp: string;
}
  1. index.ts

export interface IEnumInterface {
  stationVersionId: number;
  stationDescription ? : string;
  stationName: string;
}

export interface IEntityObj {
  id: number;
  name: string;
  type ? : ICommonEnumInterface;
}

【问题讨论】:

  • 请添加产生错误的代码。我没有在块中看到任何东西,因为组件确实安装了
  • 刚刚添加代码
  • 看起来roleDefs在您定义的状态下不存在StationListState
  • 对不起它的 StationDefs
  • StationDefs 也不见了?

标签: javascript reactjs typescript


【解决方案1】:
export interface StationListState {
  StationOnline: boolean;
  stationId: number
  appId: number;
  Activities: ActivityType;
}

您可以将 StationOnline 更改为 stationOnline 并将活动更改为活动吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-05
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 2020-02-06
    相关资源
    最近更新 更多