【问题标题】:How to setState with an Array and object in Typescript?如何在 Typescript 中使用数组和对象设置状态?
【发布时间】:2021-02-24 03:45:34
【问题描述】:

这就是我声明状态的方式

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[]) => (string | { key: string; value: string; })[]' 不可分配给类型 '(prevState: string[]) => string[]'。 类型 '(string | { key: string; value: string; })[]' 不可分配给类型 'string[]'。 键入'字符串 | {键:字符串;值:字符串; }' 不可分配给类型“字符串”。 键入'{键:字符串;值:字符串; }' 不可分配给类型 'string'.ts(2345)

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

我该如何解决这个错误?

【问题讨论】:

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


    【解决方案1】:

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

    您可以将状态更改为Array&lt;{key: string, value: string}&gt; 类型

    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

    【讨论】:

      猜你喜欢
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-16
      • 1970-01-01
      • 2019-01-10
      • 2019-10-20
      • 1970-01-01
      相关资源
      最近更新 更多