gpt4 book ai didi

reactjs - 如何为 TypeScript React 应用程序设置键/值默认状态

转载 作者:行者123 更新时间:2023-12-04 09:45:28 24 4
gpt4 key购买 nike

我必须将 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
})

...

我得到 state.hasKeys[i](属性)hashKeys:{}元素隐式具有“任何”类型,因为类型“数字”的表达式不能用于索引类型“{}”。 在类型“{}”上找不到参数类型为“数字”的索引签名。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
};

关于reactjs - 如何为 TypeScript React 应用程序设置键/值默认状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62139738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com