node.js - 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({});
})
解决方案
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)
}
推荐阅读
- java - Spring Boot Actuator - MAX 属性
- c# - 从 XML 获取数据:NetSuite WebService
- html - 如何更改触发响应的引导宽度?
- linux-kernel - 在链接描述文件中移动位置计数器和制作空白空间有什么区别
- vb.net - 如何在 VB.net 中使用 Do-While 循环?
- paramiko - Paramiko 是否与 ScaleFT 一起使用?
- apache-spark - 如何在 Spark 结构化流中刷新数据帧
- r - 在 R 中使用 dplyr 在 group_by 之后应用自定义函数
- python-3.7 - 如何在python的列表中打印用户接受的数据?
- android - 如何在隐式 Intent 上首先显示一些应用程序?