【问题标题】:How to set previous state on useState using Typescript如何使用 Typescript 在 useState 上设置先前的状态
【发布时间】:2022-01-15 23:46:52
【问题描述】:

我有当前状态: 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[]

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

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

但我不断收到以下类型错误:Argument of type '(prevState: InvoiceType | null) =&gt; { 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&lt;InvoiceType | null&gt;'

我不确定如何构建它以便解决这个问题。感谢您的帮助。

【问题讨论】:

  • 吹毛求疵:InvoiceType 是多余的 -> Invoice

标签: javascript reactjs typescript


【解决方案1】:

您将状态定义为InvoiceType | null,因此prevState 可以是null。您必须在使用前添加防护:

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

另一种方法是定义状态,使其始终具有值:useState(invoice || emptyInvoice)。然后您可以保留您的代码以供更新。

【讨论】:

  • 是的。谢谢!
  • 所以这个解决方案允许我在 prevState 存在的情况下添加表单值,但是如果它是一个新表单并且当前状态是 null 怎么办?
  • 那你就写prevState =&gt; ({... emptyInvoice, customer_name: ev.target.value})。或者可能更好,初始化状态,使其始终有一个值:useState(invoice || emptyInvoice)
猜你喜欢
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 2021-04-10
  • 1970-01-01
  • 2018-08-13
相关资源
最近更新 更多