【问题标题】:React global declare variables getting Flow type error反应全局声明变量得到流类型错误
【发布时间】:2019-01-11 05:16:54
【问题描述】:
type Props = {
checkedItems:any
};
class MyApp extends Component<Props> {
constructor(props) {
super(props);
this.checkedItems = [];
}
}
在这里,我使用 Flow 对 react 类组件进行类型检查。
当我使用 npm run flow 运行此文件时,我收到如下错误
无法将数组文字分配给this.checkedItems,因为MyApp [1] 中缺少属性checkedItems。
有人可以告诉我该怎么做才能解决流程错误
【问题讨论】:
标签:
javascript
reactjs
typescript
flowtype
【解决方案1】:
在您的代码中,您已经为道具定义了类型,但 checkedItems 不在道具中。
您需要为类变量checkedItems定义类型
interface IMyAppProps {
prop1: boolean
prop2: string
}
interface IMyAppState {
state1: number
state2: string
}
class MyApp extends Component<IMyAppProps,IMyAppState> {
checkedItems: any //defined your class variable here with any type
constructor(props) {
super(props)
this.checkedItems = []
}
}
【解决方案2】:
跑步者是正确的,类上没有定义checkedItems 属性。通过将Props 作为类型传递给Component 类,您只需定义props 类型,您需要自己在该类上定义checkedItems。
class MyApp extends Component<{}> {
checkedItems: any;
constructor(props) {
super(props);
this.checkedItems = [];
}
}