reactjs - 如何使用 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
[]
请你告诉我为什么会发生这种情况以及如何解决它,请帮助我。
问候
解决方案
问题是反应的更新状态功能是异步的。鉴于此,当您尝试将 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))
})
推荐阅读
- macos - AWK 在文件中的字符串匹配后打印
- python - 在 tkinter 上混合垂直和水平 PanedWindow() 并将窗框一起移动
- eclipse - 在 STS 4 (Eclipse 4.21.0) 中打开 .aj 文件时出错
- javascript - 不使用范围方法创建年份范围
- exchange-server - 有没有办法在 MS Exchange 中禁用加载项
- r - 在 R 中使用 rvest 进行网页抓取
- nestjs - NestJS TypeORM - 在服务初始化之前未完成加载的实体
- python - Seaborn catplot FacetGrid 轴的科学记数法?
- mongodb - Golang MongoDB 聚合查询的问题
- javascript - 等待javascript回调函数完成