【发布时间】:2020-11-18 21:52:09
【问题描述】:
我从未使用过 Typescript,试图了解它是如何工作的
这个问题非常基本,可能很简单,但我没有找到任何可以帮助我解决这个问题的资源。
问题:我想对 StationListState 中不存在但在 StationListProps 中存在的 StationDefs 设置状态,我需要将其添加到 StationListState 中吗?或以某种方式从 Station.ts 导入它,它会工作
当我尝试在 componentDidMount 中设置状态时,出现以下错误
类型参数 '{ StationDefs: any; }' 不可分配给 'StationListState | 类型的参数((上一个状态: 只读,道具:只读)=> 站列表状态 |选择<...>) |选择<...>'。对象字面量只能 指定已知属性,并且类型中不存在“StationDefs” '站列表状态 | (((prevState:只读,道具: 只读) => StationListState |选择<...>) | 选择<...>'.ts(2345)
我有 5 个文件如下
- 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() {}
}
- StationListState
interface ActivitiesType {
selectedRow: Array < number | string > ;
}
export interface StationListState {
stationOnline: boolean;
stationId: number
appId: number;
activities: ActivityType;
}
- StationListProps
//import {IStationDef} from Station.ts
export interface StationListProp {
stationDefs: IStationDef[];
}
- Station.ts
import {
IEnumInterface,
IEntityObj
} from 'index';
export interface IStationDef {
StationVersionStatus: ICommonEnumInterface
allowedUserTypes: ICommonEnumInterface;
appDef ? : IEntityObject;
appId ? : number;
timestamp: string;
}
- 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