无法显示使用 formData 修改和更新数据的 GET 方法

时间:2021-04-30 14:33:15

标签: reactjs multer form-data

我正在使用 ReactJS 和 NodeJS 进行培训并尝试更新表单。 POST 方法有效,我使用 Multer 和 formData 但我在使用 PUT/GET 方法修改数据时遇到问题。事实上,PUT 是有效的,我可以修改数据,不像 GET 显示 [object Object]。我不知道它可以从哪里来。您可以看到屏幕截图和代码,我使用的是 Material UI。 enter image description here

import useRequest from "../../../customHooks/useRequest";

const CreateCustomer = ({ className, ...rest }) => {   
const [name, setName] = useState("");   
const [description, setDescription] = useState("");   
const [chosePicture, setChosePicture] = useState([]);
const classes = useStyles();

  const handleChangeName = (e) => {
    setName(e.target.value);   };

  const handleChangeDescription = (e) => {
    setDescription(e.target.value);   };

  const { uuid } = useParams();

  const toasterSucc = () => {
    return (
      toast.success('Customer successfully created!', {
        position: "bottom-center",
        autoClose: 4000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined
      })
    );   };

  const toasterErr = (error) => {
    return (
      toast.error(`${error}`, {
        position: "bottom-center",
        autoClose: 4000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined
      })
    );   };

  const updateSubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append("cust_main_name", name);
    formData.append("cust_details", description);
    formData.append("avatar", chosePicture);
    console.log(chosePicture);
    try {
      await axios.put(`http://xxx/customers/${uuid}`, formData);
      toasterSucc();
    } catch (er) {
      er.response && toasterErr(er.response.data);
    }   };

  const { data } = useRequest("get", `http://xxx/customers/${uuid}`);

  useEffect(() => {
    if (data[0]) {
      setName(data[0]);
      setDescription(data[0]);
      setChosePicture(data[0]);
    }   }, [data]);

  return (
    <Fragment>
          <Grid>
            <Paper className={classes.mainTable}>
              <form className={classes.editForm} encType="multipart/form-data" method="post" autoComplete="off">

                <input
                  className={classes.btnfile}
                  type="file"
                  id="file"
                  name="avatar"
                  onChange={(e) => {
                  setChosePicture(e.target.files[0]);
                  }}
                />

                <TextField
                  className={classes.inputField}
                  label="Name"
                  type="text"
                  name="name"
                  value={name}
                  onChange={handleChangeName}
                  placeholder="Enter a name"
                  variant="outlined"                    
                  fullWidth
                  InputLabelProps={{
                    shrink: true,
                  }}
                />

                <TextField
                  className={classes.inputField}
                  label="Description"
                  type="text"
                  name="description"
                  value={description}
                  onChange={handleChangeDescription}
                  placeholder="Enter a description"
                  fullWidth
                  InputLabelProps={{
                    shrink: true,
                  }}
                  variant="outlined"
                />
                
              </form>
            </Paper>
          </Grid>

          <div className={classes.btnContainer}>
            <Button onClick={updateSubmit} type="submit" className={classes.button}>Save</Button>
            <ToastContainer />
          </div>

    </Fragment>   ); };

export default CreateCustomer;

useRequest 的代码:

const useRequest = (method, url, option) => {
  const [data, setData] = useState([]);
  const [error, setError] = useState("");

  useEffect(() => {
    let isSubscribe = true;
    const fetchData = async () => {
      try {
        const result = await Axios[method](url);
        if (isSubscribe) {
          setData(result.data);
        }
      } catch (err) {
        if (isSubscribe) {
          setError(err);
          setData([]);
        }
      }
    };

    if (isSubscribe) {
      fetchData();
    }

    return () => {
      isSubscribe = false;
    };
  }, [url, method, option]);

  return { data, error };
};

export default useRequest;

1 个答案:

答案 0 :(得分:1)

您将返回一个具有 objectdata 属性的 error

return { data, error };

这意味着当您在客户端获取它时,您将获取带有两个子对象的对象。您应该console.log(data )获取它并检查结果。

const { data } = useRequest("get", `http://xxx/customers/${uuid}`)

您应该只提取 data 子对象,它可能具有 namedescription 属性。