我已经和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,
}
])更新
我通过将useState声明更改为:
const [ data, setData ] = useState([]);至
const [ data, setData ] = useState<any>([]); //{type: read/write/notify/error, bin: 8 int binary, ascii: ASCII Value}然而,我意识到,这完全违背了使用TypeScript的目标。因此,我基于@tomleb3 3答案的下一步是为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[]‘类型的
参数不能分配给'DataType not (() => DataType)’类型的参数。键入'never[]‘不能分配到'() =>数据类型’。类型'never[]‘不提供签名'():DataType’的匹配。
我不知道从这里开始如何删除[] useState声明,然后将错误推到使用带有以下错误的setData()调用的地方:
类型为“any[]”的any[]参数不能分配给'SetStateAction‘类型的参数。类型“any[]”不能指定为“类型”(prevState: DataType、财政、未定义)、=> DataType、DataType、未定义‘.
发布于 2021-12-02 14:15:37
您正在接收的错误是类型记录错误,而不是反应错误。
您的代码非常好,但是在处理类型记录时,我们需要键入我们的状态以及其他所有内容。
例如,它可以如下所示:
interface State {
key1: string,
key2: number,
key3: boolean,
}
function myComponent() {
const [state, setState] = useState<State>({
key1: 'test',
key2: 42,
key3: false,
})
}这使得类型记录能够知道您的状态的结构,从而使它能够应用相关的类型保护和限制。
https://stackoverflow.com/questions/70200636
复制相似问题