在React中没有表单或按钮发布请求?

时间:2019-09-01 21:25:56

标签: javascript reactjs post

因此,我必须在没有formbutton的情况下发出发布请求。我有一个在表上呈现的patientInfo数组。当用户为患者选择位置时,该患者将具有timestamp值。当数组中的患者具有时间戳记时,就是我应该使用该时间戳记自动post患者的情况。

我的handleAutoObsSubmit()可以正常工作,但是问题是,它映射到patienArray并多次发送患者,因此如果用户选择第三位患者的位置,将会有三个相同的对象被发送的病人。

我遇到的另一个问题是componentDidUpdate,它每秒发送一次发布请求。我怀疑这是因为患者计数每秒钟都在递减。虽然不是100%肯定。在componentDidUpdate中发送发帖请求甚至是个好主意吗?

patientInfo = [
            { count: 100, room: "1", name: 'John Nero', timeStamp: '', location: ''},
            { count: 100, room: "2", name: 'Shawn Michael', timeStamp: '', location: ''},
            { count: 100, room: "3", name: 'Gereth Macneil', timeStamp: '', location: ''}
 ]
handleAutoObsSubmit = () => {

        const postUrl = '/send_patient_that_has_timeStamp';
        const timeStampedPatients = this.state.patientInfo.filter(patient => patient.timeStamp !== '');
        let data = {};

        timeStampedPatients.map((patient) => {

            data = {
                room: patient.room,
                patient: patient.name,
                timestamp: patient.timeStamp,
                location: patient.locationInfo,
            };

        });


        fetch(postUrl, {
            method: 'POST',
            body: JSON.stringify(data),
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then((res) => {

                if (!res.ok) {
                    console.log('request failed');
                } else {
                    console.log('request sent');
                }
            });
    }
 componentDidUpdate() {
        this.state.patientInfo.map(patient => {
            if (patient.timeStamp !== '') {
                this.handleAutoObsSubmit();
            }
        });
    }

componentDidMount() {
  this.countDownInterval = setInterval(() => {

            this.setState(prevState => ({

                patientInfo: prevState.patientInfo.map((patient) => {
                    if (patient.locationInfo!== '') {

                        if (patient.count <= 0) {
                            clearInterval(this.countDownInterval);
                        }
                        return { ...patient, count: patient.count - 1 };
                    }
                    return patient;
                })
            }));
        }, 1000);
    }

1 个答案:

答案 0 :(得分:0)

您应该能够以类似的方式处理它:

function Table() {
  const [tableData, setTableData] = React.useState([
    {
      name: "John Doe",
      timestamp: ""
    },
    {
      name: "Jane Doe",
      timestamp: ""
    },
    {
      name: "Nancy Doe",
      timestamp: ""
    }
  ]);

  const updateItem = (event, index) => {
    let newstate = [...tableData];
    newstate[index].timestamp = (new Date(Date.now())).toString();
    alert(`Do POST here: ${JSON.stringify(newstate[index],null,2)}`);
    setTableData(newstate);
  };
  
  return (
    <table border="5">
      <tr>
        <th>
          <div>Patient</div>
        </th>
        <th>
          <div>Timestamp</div>
        </th>
        <th>Update</th>
      </tr>
      {tableData.map((item, index) => {
        return (
          <tr>
            <td>{item.name}</td>
            <td style={{width:'410px'}}>{item.timestamp}</td>
            <td>
              <button 
                style={{backgroundColor:'green', color:'white'}} 
                onClick={event => updateItem(event, index)}>
                UPDATE
              </button>
            </td>
          </tr>
        );
      })}
    </table>
  );
}

ReactDOM.render(<Table />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>