reactjs - 如何为 TypeScript React 应用程序设置键/值默认状态
问题描述
我必须将 React 应用程序转换为 Typescript,但我无法确定属性设置散列对象的初始状态。
原版js
export default class Wizard extends PureComponent {
constructor(props) {
super(props);
this.state = this.initialState();
}
/** Setup Steps */
initialState = () => {
const state = {
activeStep: 0,
hashKeys: {},
};
// Set initial classes
// Get hash only in client side
const hash = typeof window === 'object' ? this.getHash() : '';
const children = React.Children.toArray(this.getSteps());
children.forEach((child, i) => {
// Create hashKey map
state.hashKeys[i] = (child.props && child.props.hashKey) || `step${i + 1}`;
state.hashKeys[state.hashKeys[i]] = i;
});
...
return state;
}
...
我的失败尝试
export interface TState {
activeStep?: number
hashKeys: {
[key: number]: string
}
}
export default class StepWizard extends PureComponent<{},TState> {
constructor(props: IStepWizardProps) {
super(props)
this.state = this.initialState()
}
initialState = () => {
const state = {
activeStep: 0,
hashKeys: {}, /* <---- This seems to be the problem */
}
// Set initial classes
// Get hash only in client side
const hash = typeof window === "object" ? this.getHash() : ""
const children = React.Children.toArray(this.getSteps())
children.forEach((child, i) => {
// Create hashKey map
// the following give a TS error
// ERROR: (property) hashKeys: {}
// Element implicitly has an 'any' type because expression of type 'number'
// can't be used to index type '{}'.
// No index signature with a parameter of type 'number' was found on type '{}'.ts(7053)
state.hashKeys[i] = (child.props && child.props.hashKey) || `step${i + 1}`
state.hashKeys[state.hashKeys[i]] = i
})
...
我得到 for state.hasKeys[i]
(property) hashKeys: {} Element 隐式具有“any”类型,因为“number”类型的表达式不能用于索引类型“{}”。在类型 '{}'.ts(7053) 上找不到具有类型参数的索引签名
解决方案
问题似乎来自 hashKeys 的定义为{}
.
Typescript 不知道键/值的数据类型,但是,你可以告诉它!
const hashKeys = {} as Record<number, string>;
const x = hashKeys[0];
对于您的示例:
const state = {
activeStep: 0,
hashKeys: {} as Record<string, string>, // or whatever your types are
};
推荐阅读
- spring-boot - Spring boot 运行成功结束,但嵌入式服务器已关闭
- ios - 推送通知已交付,但 didReceiveRemoteNotification 从未被称为 Swift
- css - 设置 ng-multiselect-dropdown 的宽度
- javascript - 如何区分 detail_page 和 list_page?
- r - 如何将 jpg 格式的地图转换为可以输入 geom_polygon 或 geom_sf 的 data.frame?
- azure - Azure 数据工厂数据复制源中的查找活动 - 语法错误
- javascript - 带有本地参数的 Onclick 全局函数
- python - 我在 Python Jupyter Notebook 中的代码有什么问题?
- python - 使用 zipfile 从集合中压缩文件
- excel - 避免在不同的下拉excel vba上粘贴值