【问题标题】:How to update an object using axios and json server in a react hooks project如何在反应钩子项目中使用 axios 和 json 服务器更新对象
【发布时间】:2021-07-18 07:30:26
【问题描述】:

我正在使用表格中的对话框来编辑带有 axios.patch 请求的行。单击编辑按钮时,该特定行的值将呈现到对话框中的 TextFields 中,但我无法更新这些值。谁能帮我这个?请参阅 Sandox 链接 以获得更好的理解。谢谢。

沙盒链接:https://codesandbox.io/s/material-demo-forked-gdxl3?file=/demo.js

代码:

import React, { useState } from "react";

import {
Button,
Typography,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
Table,
TableCell,
TableBody,
TableRow
} from "@material-ui/core";
import { axios } from "./Axios";
import { ValidatorForm, TextValidator } from "react-material-ui-form-validator";
import UserForm from "./UserForm";
import UserTable from "./Table";

export default function SimpleCard() {
 const [users, setUsers] = useState([]);

  const [postUser, setPostUser] = useState({
    id: "",
    name: "",
    email: ""
  });

  // console.log(users)

   const getUsers = async () => {
    const response = await axios.get("/contacts");

  if (response && response.data) {
  setUsers(response.data);
  }
  };

  React.useEffect(() => {
  getUsers();
   }, []);

  // dialog

  const [open, setOpen] = React.useState(false);
  const [fullWidth, setFullWidth] = React.useState(true);
  const [maxWidth, setMaxWidth] = React.useState("sm");

  const handleClickOpen = () => {
   setOpen(true);
  };

  const [open1, setOpen1] = React.useState(false);

  const closeDialogForm = () => {
  let userDetails = { ...postUser };

   userDetails.id = "";
   userDetails.name = "";
   userDetails.email = "";

   setPostUser(userDetails);
  };

 const handleClose = () => {
   closeDialogForm();
   setOpen(false);
 };

 const handleClose1 = () => {
   closeDialogForm();
   setOpen1(false);
 };

 const submitForm = async () => {
   const response = await axios.post("/contacts", postUser).catch((error) => {
  console.log(error);
  });

console.log(response);

if (response) {
  getUsers();
}

closeDialogForm();
};

 const openEditUserDialog = (id) => {
  let userDetails = { ...postUser };

  for (let index = 0; index < users.length; index++) {
  if (id === users[index].id) {
    userDetails.id = users[index].id;
    userDetails.name = users[index].name;
    userDetails.email = users[index].email;
  }
  }

  console.log(userDetails);

  setPostUser(userDetails);
  setOpen1(true);
 };

 const updateUser = async (id) => {
  const response = await axios
  .put(`/contacts/${id}`, postUser)
  .catch((error) => {
    console.log(error);
  });

// console.log(response)

if (response) {
  // setOpen(false);
  getUsers();
  }
 };

 const deleteUser = async (id) => {
  const response = await axios.delete(`/contacts/${id}`).catch((err) => {
  console.log(err);
  });

  if (response) {
  getUsers();
  }
  };

 return (
  <div>
  <Typography>Users</Typography>
  <Button
    size="small"
    variant="contained"
    onClick={handleClickOpen}
    style={{ textTransform: "none" }}
  >
    Add
  </Button>

  <UserTable
    users={users}
    openEditUserDialog={openEditUserDialog}
    deleteUser={deleteUser}
  />
  {/* dialog */}

  <Dialog
    fullWidth={fullWidth}
    maxWidth={maxWidth}
    open={open}
    // onClose={handleClose}
    aria-labelledby="max-width-dialog-title"
  >
    <DialogTitle id="max-width-dialog-title">Add contact</DialogTitle>

    <UserForm
      submitForm={submitForm}
      handleClose={handleClose}
      postUser={postUser}
      setPostUser={setPostUser}
    />
  </Dialog>

  {/* edit dialog */}

  <Dialog
    fullWidth={fullWidth}
    maxWidth={maxWidth}
    open={open1}
    // onClose={handleClose}
    aria-labelledby="edit-user"
  >
    <DialogTitle id="edit-user">Edit contact</DialogTitle>

    <UserForm
      submitForm={updateUser}
      handleClose={handleClose1}
      postUser={postUser}
      setPostUser={setPostUser}
    />
  </Dialog>
   </div>
 );
 }

后端json数据:

{
  "contacts": [
{
  "id": 1,
  "name": "Gowtham",
  "email": "gowtham@gmail.com"
},
{
  "id": 2,
  "name": "King",
  "email": "gowthamKing@gmail.com"
},
{
  "id": 3,
  "name": "Hello",
  "email": "gowthamKing123@gmail.com"
}
 ]
 }

【问题讨论】:

  • 尝试将您的 UI 拆分为 2 个以上的组件,以使您的代码更具凝聚力和可读性。例如,表格行可以是接收用户作为道具的组件。
  • 您能告诉我在更新值时哪里出错了吗?谢谢。

标签: reactjs axios react-hooks material-ui json-server


【解决方案1】:

我找到了解决方案。只需将updateUser 箭头函数替换为以下代码

const updateUser = async () => {

    let updateObject = {...postUser}

    const response = await axios.patch(`/contacts/${updateObject.id}`, postUser).catch(error => { console.log(error) })

    console.log(response)

    if (response) {
        // setOpen(false);
        getUsers()
    }

    handleClose1();

}

【讨论】:

    猜你喜欢
    • 2023-01-22
    • 2021-10-20
    • 2021-08-11
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 2021-11-24
    相关资源
    最近更新 更多