使用Axios PUT请求更新具有多个对象的数组中的数据 [英] Update data from array with multiple objects using Axios PUT request
本文介绍了使用Axios PUT请求更新具有多个对象的数组中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要更新数组中的数据,该数组具有多个对象,用户将在其中输入将更新旧余额状态的新余额。该数组由一个公司名称和一个名为Detail的数组组成,该数组包含包含员工信息(姓名、余额、备注)的对象,对于这个问题,我只是使用备注来简化问题。我使用Axios Put来访问嵌套对象的ID,我从通过useParams挂钩传递的链接中获取ID。
我的问题在Axios PUT请求中。以前,我有一个只是一个数据对象的模式(其中没有数组),PUT请求运行良好。然后,我需要将模式更改为具有多个对象的数组,现在似乎无法更新数据。我可以通过控制台日志来确定数据的目标,但是当我从控制台获取代码并应用它时,状态仍然没有改变。即使在Postman中,成功更新的唯一方法也是从GET请求中获取Shema,并将该模式粘贴到PUT请求中并更改其中的一些数据,然后我点击Send,它就会更新,但要让它再次更新,我需要点击Send两次(这不应该是这样的,不是吗?)。
通过两次映射,我能够访问数据并将其呈现在其他组件中,如下所示:setBalance(res.data.data.details.map((r) => r.balance));
我的问题:如何编辑以下代码以正确更新状态?
setNotes([...details, res.data.data.details.map((r) => r.notes )]);
但是,我真的很困惑如何在Axios PUT请求中做到这一点。
以下是我的代码:
import React, { useState } from "react";
import { useHistory } from "react-router-dom";
import { useParams } from "react-router-dom";
import axios from "axios";
const AddForm = () => {
const [newBalance, setNewBalance] = useState("");
const [details, setDetails] = useState([]);
const [notes, setNotes] = useState("");
const [total, setTotal] = useState("");
const { id } = useParams();
const history = useHistory();
//update balance
const updateBal = () => {
// function to calculate balance
};
const updateBalHandler = (e) => {
e.preventDefault();
axios({
method: "PUT",
url: `http://localhost:5000/update-snapshot-test/${id}`,
data: {
balance: total
notes: notes
},
}).then((res) => {
history.push(`/success/` + id);
setNotes([...details, res.data.data.details.map((r) => r.notes )]); //this code isolates the notes state but does not update it
});
};
return (
<form
action="/update-snapshot/:id"
method="post"
onSubmit={updateBalHandler}
>
<Input
setInputValue={setNewBalance}
inputValue={newBalance}
inputType={"number"}
/>
<Input
setInputValue={setTotal}
inputValue={total}
inputType={"number"}
/>
<TextArea
setInputValue={setNotes}
inputValue={notes}
inputType={"text"}
/>
<Button onClick={() => { updateBal(); }} >
Update
</Button>
<Button type="submit">
Save
</Button>
</form>
);
};
export default AddForm;
这是我从Mongo DB获取的数据结构
{
"message": "Post found",
"data": {
"company": "Riteaid",
"_id": "1",
"details": [
{
"employee": "jane doe",
"balance": "3",
"notes": "some notes",
"_id": "2"
},
{
"employee": "john doe",
"balance": "1",
"notes": "some more notes",
"_id": "3"
}
],
}
}
推荐答案
答案在后端,前端很好,代码不需要任何添加,应该是:
const addBalHandler = (e) => {
e.preventDefault();
axios({
method: "PUT",
url: `http://localhost:5000/endpoint${id}`,
data: {
balance: total,
notes: notes,
date: date,
},
}).then((res) => {
history.push(`/success/` + id);
console.log(res.data);
});
};
这篇关于使用Axios PUT请求更新具有多个对象的数组中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文