简体   繁体   English

如何用数组和Typescript中的object设置状态?

[英]How to setState with an Array and object in Typescript?

This is how I declare a state这就是我声明 state 的方式

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

and this is my error code:这是我的错误代码:

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

This is a typescript hint:这是一个 typescript 提示:

Argument of type '(curGoals: string[]) => (string | { key: string; value: string; })[]' is not assignable to parameter of type 'SetStateAction<string[]>'. “(curGoals: string[]) => (string | { key: string; value: string; })[]”类型的参数不可分配给“SetStateAction<string[]>”类型的参数。 Type '(curGoals: string[]) => (string | { key: string; value: string; })[]' is not assignable to type '(prevState: string[]) => string[]'.类型 '(curGoals: string[]) => (string | { key: string; value: string; })[]' 不可分配给类型 '(prevState: string[]) => string[]'。 Type '(string | { key: string; value: string; })[]' is not assignable to type 'string[]'.类型 '(string | { key: string; value: string; })[]' 不可分配给类型 'string[]'。 Type 'string |输入'字符串| { key: string; { 键:字符串; value: string;值:字符串; }' is not assignable to type 'string'. }' 不可分配给类型 'string'。 Type '{ key: string;输入'{键:字符串; value: string;值:字符串; }' is not assignable to type 'string'.ts(2345) }' 不可分配给类型 'string'.ts(2345)

I still don't understand why my code still outputs this error.我仍然不明白为什么我的代码仍然输出这个错误。 I did use a string type of array with useState.我确实在 useState 中使用了字符串类型的数组。

How can I resolve this error?我该如何解决这个错误?

You declare the state as being string[] this means it is an array of strings.您将 state 声明为string[]这意味着它是一个字符串数组。 So an item of this state must be a string .所以这个 state 的一项必须是一个string { key: Math.random().toString(), value: input } is an object with properties value and key property of type string . { key: Math.random().toString(), value: input }是一个 object,具有valuekey类型的属性string

You can change the state to be of type Array<{key: string, value: string}>您可以将 state 更改为Array<{key: string, value: string}>类型

const [input, setInput] = React.useState('')
const [goals, setGoals] = React.useState<
    Array<{
        key: string,
        value: string
    }>
>([])

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

Playground Link 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM