【发布时间】:2019-11-17 15:53:26
【问题描述】:
我正在开发使用 TypeScript 和 React 的项目,并且我正在尝试根据分配给状态的接口来限制数据。
我已将 IState interface 类型分配给具有 uiForm 键分配类型 studentForm interface 的状态。但是,当我将错误的结构化数据或在 studentForm 接口中不存在的错误键分配给 uiForm 键时,它会在未验证类型的情况下被分配。
我的代码如下所示:
interface IProps {}
interface studentForm {
label: string,
type: string,
sequen: string
}
interface IState {
uiForm: Array < studentForm >
}
export default class AddStudent extends React.Component < IProps, IState > {
state: IState = {
uiForm: []
}
constructor(props: IProps) {
super(props);
}
componentDidMount() {
fetch('./assets/studentForm.json').then((res) => res.json())
.then((data) => {
this.setState({
uiForm: data
})
})
.catch(err => {
console.log(err);
})
}
}
我正在尝试用下面的对象分配 uiForm
studentForm.json:
{
"label":"Admission No.",
"type":"text",
"sequence":1
}
理想情况下,它不应该被分配,但它正在分配
将类型分配给 state/setState 的正确方法是什么? 谢谢。
【问题讨论】:
-
下面的答案是否解决了您的问题?
标签: reactjs typescript