首页 > 解决方案 > 使用 Axios PUT 请求从具有多个对象的数组中更新数据

问题描述

我需要更新具有多个对象的数组中的数据,用户将在其中输入将更新旧余额状态的新余额。该数组由一个公司名称和一个名为 details 的数组组成,该数组包含包含员工信息(姓名、余额、注释)的对象,对于这个问题,我只是使用注释来简化事情。我正在使用 Axios PUT 访问嵌套对象的 id,我从通过 useParams 钩子传递的 Link 获取 id。

我的问题出在 Axios PUT 请求中。在我有一个只是一个数据对象的模式(其中没有数组)并且 PUT req 工作正常之前。然后我需要将架构更改为包含多个对象的数组,现在我似乎无法更新数据。我可以通过控制台日志定位数据,但是当我从控制台获取该代码并应用它时,状态仍然没有改变。即使在 Postman 中,我成功更新的唯一方法是从 GET 请求中获取 Shema 并将该模式​​粘贴到 PUT 请求中并更改其中的一些数据,然后我点击发送并更新,但要让它更新再次我需要点击发送两次(这不应该,不是吗?)。

我可以通过两次映射来访问数据并将其呈现在其他组件中,如下所示: 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"
            }
        ],
    }
}

标签: reactjsloopsaxiosnested-loops

解决方案


你有 id,所以你必须搜索相关的对象,更新它并将它传递给setNotes()setter。

let localNotes = res.data.data.details.map((responseDetail) => {
    if (detail._id === id){
        let newNotes = [...responseDetail.notes, ...details];
        return {
            ...responseDetail,
            notes: newNotes
        };
    }
    return responseDetail;
});
if (localNotes.length){
    setNotes(localNotes);
}

这能解决你的问题吗?


推荐阅读