简体   繁体   English

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

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

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

My type for InvoiceType is:我的InvoiceType类型是:

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

I am trying to modify state in my form to modify previous state using an input field like follows:我正在尝试在我的表单中修改 state 以使用如下输入字段修改以前的 state:

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

But I keep getting the following Type error: 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>' 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>'

I am not sure how to structure this so that I can get around this issue.我不知道如何构建它以便我可以解决这个问题。 Thanks for the help.谢谢您的帮助。

You defined the state as InvoiceType | null您将 state 定义为InvoiceType | null InvoiceType | null , so prevState can be null . InvoiceType | null ,所以prevState可以是null You must add a guard before using it:您必须在使用前添加防护:

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

The another approach is to define the state so it always has a value: useState(invoice || emptyInvoice) .另一种方法是定义 state 所以它总是有一个值: useState(invoice || emptyInvoice) And then you can keep your code for the update.然后您可以保留您的代码以进行更新。

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

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