首页 > 解决方案 > 如何在 POST 请求中编辑数据

问题描述

我有一个patientStatus()函数,onClick 它将设置为p.status单击按钮的 id,同时它创建一个保存为值的时间戳p.timestamp。这patient's datapatients 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: ''},
                 ]
              }

标签: javascriptreactjs

解决方案


向 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


推荐阅读