尽管我已经为我的某个状态的初始状态提供了接口(interface),但我仍然无法弄清楚为什么 TS 会抛出一堆错误。
任何人都可以帮我解决下面的代码吗?
interface initialStateProps {
eventInfo: {
name: string;
location: string;
}
}
class Dashboard extends Component<RouteComponentProps> {
//what is wrong here? ts showing bunch of error?
const [formValues, setFormValues] = useState<initialStateProps>({
eventInfo: {
name: '',
location: ''
}
})
return <div></div>
}
最佳答案
您似乎正在尝试使用 React 功能组件,因为您正在使用 useState钩。
在这种情况下,您不应该创建一个类并从 React.Component
扩展它,因为这些用于定义类组件。
这是使用 React 和 TypeScript 定义功能组件的方法。
interface initialStateProps {
eventInfo: {
name: string;
location: string;
}
}
const Dashboard: React.FC = () => {
const [formValues, setFormValues] = useState<initialStateProps>({
eventInfo: {
name: '',
location: ''
}
})
return <div></div>
};
关于javascript - 为什么 typescript 在 useState React 上抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61134545/