如何在Typescript中使用数组和对象设置setState?

时间:2020-11-12 06:14:22

标签: arrays typescript react-native react-hooks use-state

这就是我声明状态的方式

const [input, setInput] = React.useState('')
const [goals, setGoals] = React.useState<string[]>([])

这是我的错误代码:

const addHandler = () => {
    setGoals((curGoals) => [...curGoals, { key: Math.random().toString(), value:input}])
}

这是打字稿提示:

'(curGoals:string [])=>(string | {key:string; value:string;})[]'类型的参数不能分配给'SetStateAction '类型的参数。 类型'(curGoals:string [])=>(字符串| {键:字符串;值:字符串;})[]'不能分配给类型'(prevState:string [])=> string []'。 类型'(string | {键:字符串;值:字符串;})[]'不能分配给类型'string []'。 输入'string | {键:字符串;值:字符串; }”不可分配给“字符串”类型。 输入'{键:字符串;值:字符串; }'不能分配给'string'.ts(2345)

我仍然不明白为什么我的代码仍然输出此错误。我确实使用了useState的字符串类型的数组。

如何解决此错误?

1 个答案:

答案 0 :(得分:1)

您将状态声明为string[],这意味着它是一个字符串数组。因此,此状态的项必须为string{ key: Math.random().toString(), value: input }是具有属性value和类型key的{​​{1}}属性的对象。

您可以将状态更改为string

Array<{key: string, value: string}>

Playground Link