【发布时间】:2022-01-09 00:20:51
【问题描述】:
更新
我通过将我的 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
}
但这会报错:
“never[]”类型的参数不能分配给类型参数 '数据类型 | (() => 数据类型)'。类型 'never[]' 不可分配给 输入“()=>数据类型”。 类型 'never[]' 与签名 '(): DataType' 不匹配。
我不知道如何从这里开始,因为删除 [] useState 声明然后将错误推送到我使用 setData() 调用的任何地方,并出现以下错误:
'any[]' 类型的参数不能分配给类型参数 'SetStateAction'。类型 'any[]' 不是 可分配给类型 '(prevState: DataType | undefined) => DataType | 未定义'。
原帖
我已经使用 react / typescript 工作了几天,并且正在通过做一个小项目来自学。作为其中的一部分,我目前正在将一些基于类的代码转换为钩子。
我有以下基于 (js) 类的代码,我不知道如何将其转换为在带有 typescript 的钩子中使用:
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,
}
])
任何指针/解决方案将不胜感激。
谢谢。
【问题讨论】:
-
如果你的状态类型最终是
DataType对象的数组,那么正确的语法是const [ data, setData ] = useState<DataType[]>([]); -
@tomleb3 当然可以。谢谢!
标签: reactjs typescript ionic-framework react-hooks