如何在 react hooks 项目中使用 axios 和 json 服务器更新对象

问题描述

我正在使用表格中的对话框编辑带有 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"
}
 ]
 }

解决方法

我找到了解决方案。只需用下面的代码替换 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();

}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...