繁体   English   中英

如何使用 Typescript 在 useState 上设置以前的 state

[英]How to set previous state on useState using Typescript

我有当前的 state: const [newInvoice, setInvoice] = useState<InvoiceType | null>(invoice) const [newInvoice, setInvoice] = useState<InvoiceType | null>(invoice)

我的InvoiceType类型是:

  customer_email: string
  customer_name: string
  description: string
  due_date: string
  status: FilterButtonState
  total: number
  line_items: LineItemType[]

我正在尝试在我的表单中修改 state 以使用如下输入字段修改以前的 state:

<input
   ...otherAttributes
   onChange={(ev: React.ChangeEvent<HTMLInputElement>): void =>
   setInvoice((prevState) => ({
      ...prevState,
       customer_name: ev.target.value
    }))
/>

但我不断收到以下类型错误: Argument of type '(prevState: InvoiceType | null) => { customer_name: string; customer_email?: string | undefined; description?: string | undefined; due_date?: string | undefined; status?: FilterButtonState | undefined; total?: number | undefined; line_items?: LineItemType[] | undefined; }' is not assignable to parameter of type 'SetStateAction<InvoiceType | null>' Argument of type '(prevState: InvoiceType | null) => { customer_name: string; customer_email?: string | undefined; description?: string | undefined; due_date?: string | undefined; status?: FilterButtonState | undefined; total?: number | undefined; line_items?: LineItemType[] | undefined; }' is not assignable to parameter of type 'SetStateAction<InvoiceType | null>'

我不知道如何构建它以便我可以解决这个问题。 谢谢您的帮助。

您将 state 定义为InvoiceType | null InvoiceType | null ,所以prevState可以是null 您必须在使用前添加防护:

prevState => prevState ? { ...prevState, customer_name: ev.target.value } : null

另一种方法是定义 state 所以它总是有一个值: useState(invoice || emptyInvoice) 然后您可以保留您的代码以进行更新。

暂无
暂无

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

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