reactjs - 传递空数组时如何将useState与Typescript一起使用
问题描述
我正在尝试将我的 JSX 代码转换为 typescript (TSX),并且在使用useState钩子时难以通过接口。我想要的只是在我的状态下的空数组接口,并且在更新时我将对象一一推送到数组。
我在更新计数时收到类型错误“'any []' 类型的参数不可分配给'SetStateAction' 类型的参数。类型'any []' 不可分配给类型'(prevState:IData)=> IData' . 类型 'any[]' 与签名 '(prevState: IData): IData' 不匹配
这是我所做的代码:
样本.tsx
const interface IData {
id: number
value: string
}
const Sample = () => {
let [count, setCount] = useState<IData>([]); <------------ Want to know how to pass the blank interface or Array and also how to update interface once values are pushed to the Array
const addCount = () => {
setCount([...count, {
id: count.length,
value: 'Condition ' + count.length
}])
}
const handleRemove = (id:number) => {
console.log(id);
const count_upd = count.filter((item:any) => item.id != id);
setCount(count_upd);
}
return(
<React.Fragment>
<Container>
{ Array(count).fill(<ConditionSeg Data={count.map((item:IData) => (
item.id,item.value
))}
HandleRemove ={handleRemove}
/>)}
</Container>
<Container>
<Button
onClick={addCount}>
Click me</Button>
</Container>
</React.Fragment>
)
}
PS 不要介意类型错误。
解决方案
据我所知,您想要存储一个 type 值的数组IData
。在这种情况下,您应该使用
let [count, setCount] = useState<IData[]>([]);
这意味着,您正在存储一个 type 值的数组IData
。在您上面的情况下,您忘记了数组括号,因此 setCount 实际上会期望一个类型的对象IData
而不是数组。
推荐阅读
- css - 如何在反应中更改 ag-grid 的 bg 颜色?
- c# - 如何直接从 datagridview 单元格更新 SQL 记录,而不使用文本框?
- c# - InvalidOperationException:列出但应该是 vm 值
- css - 为什么弹性按钮的孩子不能伸展到全高?
- c - 找不到英特尔 C++ 编译器 17.0(平台工具集 = '英特尔 C++ 编译器 17.0')的构建工具
- python - 使用 json 从 instagram 收集数据
- scorm - SCORM 内容中的 AJAX
- azure - Azure 管道 BatchScript 任务未在其部署到的计算机上运行脚本
- asp.net - Angular 8 httpclient如何发送JSON标头
- latex - 如何在 dev.to 编辑器中使用 Latex?