简体   繁体   English

设置对象的 useState 数组的类型

[英]Setting type for useState array of objects

I'm struggling to figure out what the problem is with my code.我正在努力弄清楚我的代码有什么问题。

interface history { 
  data: string, 
  przed: string | number, 
  po: string | number,
}

I have an interface outside of the Functional Component then inside I define how it's supposed to look like - no problem我在功能组件之外有一个接口,然后在内部定义它的外观 - 没问题

const [history, setHistory] = useState<[history]>([{
    data: '',
    przed: '',
    po: '',
}]);

then I have a onClick function which does this:然后我有一个 onClick function 这样做:

    setHistory([ ... history , {
      data: new Date().toISOString().slice(0, 10), // date
      przed: fromTo, // number
      po: valueToSave, // number
    }]);

Everything works fine when compiled and tested in the browser, however VS Code is not liking my code at all with this error:在浏览器中编译和测试时一切正常,但是 VS Code 根本不喜欢我的代码并出现此错误:

Argument of type '[history, { data: string; przed: number; po: string; }]' is not assignable to parameter of type 'SetStateAction<[history]>'.
  Type '[history, { data: string; przed: number; po: string; }]' is not assignable to type '(prevState: [history]) => [history]'.
    Type '[history, { data: string; przed: number; po: string; }]' provides no match for the signature '(prevState: [history]): [history]'.ts(2345)

How can I handle something like this?我该如何处理这样的事情? What does it mean?这是什么意思?

You can use either history[] or Array<history> instead of [history] which means you want an array of history type or an array in which each elements will be of type history .您可以使用history[]Array<history>而不是[history]​​这意味着您需要一个history类型的数组或一个数组,其中每个元素的类型都是history

[history] means that it has an array that will contain an element of type history [history]​​表示它有一个数组,其中包含一个history类型的元素

history[] means you it is an array of type history history[]意味着你它是一个history类型数组

const [history, setHistory] = useState<history[]>([
    {
      data: "",
      przed: "",
      po: ""
    }
  ]);

or you can also do as:或者你也可以这样做:

  const [history, setHistory] = useState<Array<history>>([
    {
      data: "",
      przed: "",
      po: ""
    }
  ]);

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

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