【问题标题】:Update data from array with multiple objects using Axios PUT request使用 Axios PUT 请求从具有多个对象的数组中更新数据
【发布时间】:2021-07-25 03:34:15
【问题描述】:

我需要更新具有多个对象的数组中的数据,用户将在其中输入一个新的余额,该余额将更新旧的余额状态。该数组由一个公司名称和一个名为 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"
            }
        ],
    }
}

【问题讨论】:

  • details 变量包含什么?它似乎是空的(从我在代码中看到的)
  • 如问题详细信息中所述,在此问题“注释”的情况下,该对象包含所有员工信息
  • details 对象包含result.data.data 中的对象之一的注释?
  • 是的,没错

标签: reactjs loops axios nested-loops


【解决方案1】:

你有 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);
}

这能解决您的问题吗?

【讨论】:

  • 谢谢这不起作用,细节没有定义,所以我把它改成了细节,但仍然不起作用。还有一个问题,我是否将这个代码块放在Axios请求中?。
  • 是的,在'then'块中
【解决方案2】:

答案在后端,前端很好,代码不需要任何添加,应该是:

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);
    });
  };

【讨论】:

    猜你喜欢
    • 2021-04-08
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多