首页 > 解决方案 > 传递空数组时如何将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 不要介意类型错误。

标签: reactjstypescriptreact-hooks

解决方案


据我所知,您想要存储一个 type 值的数组IData。在这种情况下,您应该使用

let [count, setCount] = useState<IData[]>([]);

这意味着,您正在存储一个 type 值的数组IData。在您上面的情况下,您忘记了数组括号,因此 setCount 实际上会期望一个类型的对象IData而不是数组。


推荐阅读