首页 > 解决方案 > 如何使用 reactjs 和 typescript 在方法提交中保存数组

问题描述

我对以下代码有疑问:

type Formdata{
   title: string
   cant: number
   description
}
// I replace this code to the another code any[], but not
// resolving the problem
// const [sendData, SetsendData] = React.useState<Formdata[]>([])    
const [sendData, SetsendData] = React.useState<any[]>([]) //MYBE PROBLEM HERE
//
const onSubmit = handleSubmit(({title, cant, description})=>{
   let data_send = {
       title: title,
       cant: cant,
       description: description
   }
   // PROBLEM HERE THE FIRST CLICK
   // BUT THE SENCOND CLICK WORKING
   SetsendData(prev=>[...prev, data_send]) // MYBE PROBLEM HERE
   // first click, display undefined
   console.log(sendData)
   //
   window.localStorage.setItem("formreward", JSON.stringify(sendData))
   // in the localStorage save data like this
   // 0: {title: "title one", cant:37, description: "description"}
   // 1: {title: "title two", cant:37, description: "description2"} 
})

return(
    <form onSubmit={onSubmit}>
      <input type="text" name="title" />
      <input type="number" name="cant" />
      <input type="text" name="description" />
       <button>save</button>
    </form>
)

问题是第一次点击,不保存任何东西,控制台日志,显示未定义,但第二次点击确实保存数据,这是一个问题,因为刷新页面时,并尝试保存数据,删除localStorage中的所有数据。下面的例子:

// FIRST CLICK DOESN'T SAVE ANYTHING
[]
// SECOND CLICK WITHOUT REFRESH PAGE
[0: {title: "title one", cant:37, description: "description"}]
// ANOTHER CLICK WITHOUT REFRESH PAGE
[
  0: {title: "title one", cant:37, description: "description"}
  1: {title: "title Two", cant:44, description: "description2"}
]
// WORKING WELL
//
// BUT, WHEN THE REFRESH PAGE AND THE FIRST CLICK 
// DELETE ALL DATA SAVED
[]

请你告诉我为什么会发生这种情况以及如何解决它,请帮助我。

问候

标签: reactjstypescriptlocal-storage

解决方案


问题是反应的更新状态功能是异步的。鉴于此,当您尝试将 setItem 设置为 localStorage 时,您sendData尚未更新。您可能希望用于useEffect监听senData状态变化并相应地触发setItem,例如:

useEffect(() => 
  window.localStorage.setItem("formreward", JSON.stringify(sendData)),
  [sendData])

这样,在 sendData 状态更新时,您的 localStorage 将正确设置它。

另一种方法是在调用更新状态之前将下一个状态设置为变量:

const onSubmit = handleSubmit(({title, cant, description})=>{
   let data_send = {
       title: title,
       cant: cant,
       description: description
   }

   const nextState = [...sendData, data_send]
   SetsendData(nextState)
   window.localStorage.setItem("formreward", JSON.stringify(nextState))
})

推荐阅读