Converting class based js useState array to typescript Hook问题

Converting class based js useState array to typescript Hook problem


更新

我通过更改我的 useState 声明来实现此功能:

const [ data, setData ] = useState([]);

const [ data, setData ] = useState<any>([]); //{type: read/write/notify/error, bin: 8 int binary, ascii: ASCII Value}

然而,我意识到这恰恰违背了使用 Typescript 的目的。因此,基于@tomleb3 的回答,我的下一步是为 data 创建一个接口,如下所示:

const [ data, setData ] = useState<DataType>([]); //{type: read/write/notify/error, bin: 8 int binary, ascii: ASCII Value}
  
  interface DataType{
    chx: any,
    bin: string,
    type: string,
    ascii: string
  }

但这给出了一个错误:

Argument of type 'never[]' is not assignable to parameter of type 'DataType | (() => DataType)'. Type 'never[]' is not assignable to type '() => DataType'. Type 'never[]' provides no match for the signature '(): DataType'.

我不知道如何从这里开始,因为删除 [] useState 声明然后将错误推到我使用 setData() 调用的任何地方,并出现以下错误:

Argument of type 'any[]' is not assignable to parameter of type 'SetStateAction<DataType | undefined>'. Type 'any[]' is not assignable to type '(prevState: DataType | undefined) => DataType | undefined'.


原创POST

我已经使用 react / typescript 工作了几天,并且正在通过做一个小项目来自学。作为其中的一部分,我目前正在将一些基于 class 的代码转换为钩子。

我有以下基于 (js) class 的代码,我不知道如何将其转换为在带有打字稿的钩子中使用:

this.setState({
  data: [
    ...this.state.data,
    {
      chx: chx,
      type: type,
      bin: bin,
      ascii: ascii,
    },
  ],
});

在基于钩子的等效项中,我知道我会使用 setData(); 来表示简单状态。但是,如何转换上面的示例?我的尝试(如下)显然是错误的,因为我收到了错误:Type '{ chx: unknown; type: string; bin: string; ascii: string; }' is not assignable to type 'never'. 但我仍然坚持下一步应该做什么来尝试解决这个问题:

setData([
  ...data,
  {
    chx: chx,
    type: type,
    bin: bin,
    ascii: ascii,
  }
])

任何指示/解决方案将不胜感激。

谢谢。

您收到的错误是 Typescript 错误,而不是 React 错误。
您的代码非常好,但是在使用 Typescript 时,我们需要像输入其他所有内容一样输入我们的状态。

例如,它看起来像这样:

interface State {
   key1: string,
   key2: number,
   key3: boolean,
}

function myComponent() {
   const [state, setState] = useState<State>({
      key1: 'test',
      key2: 42,
      key3: false,
   })
}

这允许 Typescript 了解您的状态结构,从而使其能够应用相关的类型保护和限制。