javascript - 如何在 POST 请求中编辑数据
问题描述
我有一个patientStatus()
函数,onClick 它将设置为p.status
单击按钮的 id,同时它创建一个保存为值的时间戳p.timestamp
。这patient's data
是patients array
在发布请求上发送的,('/observation/record')
以保存在数据库中。
现在,如果我想编辑保存的记录,我需要之前获取并传递replace: lastTimestamp
给同一个 post 端点的时间戳。
Edit behavior
- 当我第一次单击该按钮时,它应该只是在带有时间戳的帖子上发送数据,但如果我单击再次或另一个按钮,那么这是一个编辑,然后我需要发送另一个帖子请求lastTimeStamp 并用新的替换它。
我可以进行初始发布并使用时间戳保存数据,但我不完全知道如何执行代码/逻辑进行编辑。该设计也没有编辑按钮。每当调用 patienStatus onClick 时,都会在帖子中发送数据。
patientStatus = (e, patient) => {
const { id } = e.target;
this.setState({
patients:
this.state.patients.map(p => {
if (p.id === patient.id) {
const timestamp = Date.now(); //create a timestamp
return { ...p, status: id, timestamp };
}
return p;
}),
}, () => {
this.postObservationRecord(patient);
});
}
postObservationRecord(patient) {
this.state.patients.map(p => {
if ((p.id === patient.id ) && (p.timestamp)) {
axios({
method: 'post',
url: '/observation/record',
data: {
room: p.room,
patient: p.id,
timestamp: p.timestamp,
presentation: p.status,
}
})
.then(res => {
if(res.status === 200 && res.statusText === 'OK') {
console.log('request sent');
}else {
console.log('request failed');
}
})
.catch(err => { throw new Error(err); });
}
});
}
<div>
<Button id="Awake" onClick={(e) => patientStatus(e, patient,)}> Awake </Button>
<Button id="Asleep" onClick={(e) => patientStatus(e, patient)}>Asleep</Button>
</div>
this.state = {
patients: [
{ room: "1", name: 'John', timestamp: ‘’ , status: ''},
{ room: "2", name: 'Shawn', timestamp: ‘’, status: ''},
]
}
解决方案
向 state添加一个新字段lastTimeStamp
,该字段维护当前 timeStamp 的先前值并将其沿 Axios 主体发送,但这是糟糕的系统设计。
我认为您正在尝试使用其时间戳访问一行。相反,我会通过以下方式完成它:
在发布请求时:
客户端:
客户端发送包含字段的数据room, name and status
。
服务器端:
服务器接收字段room, name and status
。服务器在收到请求后生成时间戳和主键,并与字段一起存储到数据库中。primary-key, room, name, status and timestamp
将包含所有字段的响应发送给客户端。
在编辑(即 PUT)请求时:
客户端:
客户端发送包含字段的数据new-room, new-name, new-status and primary-key
(在发布响应中收到)
服务器端:
服务器接收new-room, new-name, new-status and primary-key
。服务器在接收到请求后确定使用哪个表行来更新primary-key
。然后它使用字段更新数据库表new-room, new-name, and new-status
推荐阅读
- excel - 使用 VBA 进行自定义排序的意外结果
- php - 用 WooCommerce 产品变体上的文本替换空白和零显示价格
- azure-devops - 从另一个项目中获取库并在构建管道中通过 YAML 在新项目中引用它们
- python - 使用 python 更改 ntriples 文件
- java - 使用 rest 调用更新 xml 文件路径
- java - 如何超快速地插入 100,000 个父行和 200 个子行?
- unity3d - 在 Unity3D 中,“设置”网格的边界会做什么或实现什么?
- angular - 从Angular 7中的模板获取HTML元素
- r - 我无法将数组中的向量而不是整个数组称为单个向量
- git - 将 git repo 完全重置为克隆状态?