首页 > 解决方案 > React-Hooks PUT 在单击时从对象请求特定字段

问题描述

如何发出 PUT 请求并仅针对 patient.status 并将其从 Active 更改为 Inactive?我不想改变整个病人,只改变病人状态。

请记住,我想使用 fetch(),我只是不知道如何仅编辑 patient.status 并将其传递给我的后端等的语法。帮助将不胜感激。

我以这种方式从特定患者那里获取数据并声明状态。

const [patient, setPatient] = useState ({})

useEffect(() => {
    fetch(`/api/patients/${match.params.id}`)
    .then(response => response.json())
    .then(json => setPatient(json))

}, [patient])

提交功能。

const onDeactivePatientSubmit = (e) => {
    e.preventDefault()
}

按钮。

     { patient.status === "Active" &&
      <Button size="small" color="primary" variant="outlined" onClick={onDeactivePatientSubmit} 
value="Inactive">DE-ACTIVATE PATIENT</Button>
            }

后端。(请记住我想保持 req.body.editPatient 原样)

router.put('/:id', async (req, res) => {
    const {id} = req.params;
    await Patient.findByIdAndUpdate(id, {...req.body.editPatient});
    console.log(req.body.editPatient)
    res.status(200).send({});
})

标签: node.jsreactjsmongodbexpressreact-hooks

解决方案


fetch接受第二个参数,一个选项对象,您可以在其中设置要使用的方法、要发送的数据等。您可以使用扩展运算符创建新的/更新的患者对象。它将复制获取的patient对象,您可以更新该status字段。您可以通过以下方式发送这个新对象fetch

const onDeactivePatientSubmit = (e) => {
  e.preventDefault()
  
  let updatedPatient = {
    ...patient,
    status: 'Inactive',
  }

  fetch(`/api/patients/${patient.id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    // the data to send
    body: JSON.stringify({ editPatient: updatedPatient })
  })
  .then(res => res.json())
  .then(data => {
    // check if successfully updated in db
    setPatient(updatedPatient)
}

推荐阅读