首页 > 解决方案 > 将参数传递给函数反应失败

问题描述

我有这个。这是我的整个页面,以避免任何混淆。

 import React, { useState, useEffect } from "react";
import axios from "axios";

const TourPage = () => {
  const [myData, setMyData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [showEditButton, setShowEditButton] = useState(false);

  useEffect(() => {
    axios
      .get("/getResults")
      .then((res) => {
        setMyData(res.data);
        setIsLoading(true);
      })
      .catch((error) => {
        // Handle the errors here
        console.log(error);
      })
      .finally(() => {
        setIsLoading(false);
      });
  }, []);

  const deleteById = (id) => {
    console.log(id);
    axios
      .post(`/deleteDoc`, { id: id })
      .then(() => {
        console.log(id, " worked");
        window.location = "/tour";
      })
      .catch((error) => {
        // Handle the errors here
        console.log(error);
      });
  };

  const editById = (id, siteLocation, Services, cnum) => {
    console.log(id, siteLocation, Services, cnum);
    axios
      .post(
        `/editDoc`,
        JSON.stringify({
          id: id,
          location: siteLocation,
          Services: Services,
          cnum: cnum
        }),
        {
          headers: {
            "Content-Type": "Application/json"
          }
        }
      )
      .then(() => {
        console.log(id, " worked");
        window.location = "/tour";
      })
      .catch((error) => {
        // Handle the errors here
        console.log(error);
      });
  };

  const onClickEdit = (e, _id) => {
    e.preventDefault();
    var siteLocation = document.getElementById("location").value;
    var Services = document.getElementById("Services").value;
    var cnum = document.getElementById("cnum").value;
    console.log(siteLocation, Services, cnum)
    editById(_id, siteLocation, Services, cnum);
  };

  const onTyping = (value) => {
    if (value.length > 0) {
      setShowEditButton(true);
    } else {
      setShowEditButton(false);
    }
  };

  return (
    <table id="customers">
      <tr>
        <th>siteLocation</th>
        <th>Services</th>
        <th>cnum</th>
      </tr>
      {myData.length > 0 &&
        myData.map(({ location, Services, cnum, _id }, index) => (
          <tr key={index}>
            <td>
              <input
                type="text"
                placeholder={location}
                onChange={(e) => onTyping(e.target.value)}
                name="location"
                id="location"
              />{" "}
            </td>
            <td>
              <input
                type="text"
                placeholder={Services}
                name="Services"
                id="Services"
              />{" "}
            </td>
            <td>
              <input
                type="text"
                placeholder={cnum}
                name="cnumhide"
                id="cnumhide"
              />{" "}
            </td>
            <td>
              <input type="hidden" placeholder={cnum} name="cnum" id="cnum" />{" "}
            </td>
            <button
              onClick={(e) => {
                e.preventDefault();
                deleteById(_id);
              }}
              disabled={isLoading}
            >
              Delete
            </button>
            {showEditButton && (
              <button onClick={(e) => onClickEdit(e, _id)}>Submit Edit</button>
            )}
          </tr>
        ))}
      {myData.length === 0 && "No Data Found"}
    </table>
  );
};

export default TourPage;

我的问题是,当我单击submit edit按钮时,没有任何参数传递到后端或editById函数。我希望能够获取参数的值并通过后端在 mongodb 中更新它们。我该如何解决?我尝试了其他方法,但我认为 document.getElementById 可能无法正常工作。这可能是问题所在,但即便如此,我也不知道在哪里或如何解决。谢谢

标签: javascripthtmlreactjs

解决方案


如果必须使用 html 参考:(不建议)

似乎您无法从中获取值getElementById。在 React 应用程序中使用 DOM 操作是一种反模式。相反,如果必须,请使用useRef 挂钩

例子:

import {useRef} from 'react'

const TourPage = () => {
  ...
  const cnumRef = useRef()
  const servicesRef = useRef()
  const siteLocationRef = useRef()
  ...

  const onClickEdit = (e, _id) => {
    e.preventDefault();
    var siteLocation = siteLocationRef.current;
    var Services = servicesRef.current;
    var cnum = cnumRef.current;
    console.log(siteLocation, Services, cnum)
    editById(_id, siteLocation, Services, cnum);
  };
  
  /* passing them to the html */
  return (
    ...
    <input
      ref={Services.ref}
      type="text"
      placeholder={Services}
      name="Services"
      id="Services"
    />
  )

}

建议

尽管 refs 在这种情况下可以工作,但我强烈建议useState为每个输入使用和创建单独的状态变量。useRef如果值发生变化,则不会重新渲染,因此我会改为:

import {useState} from 'react'

/* inside component: */
const [fields, setFields] = useState({
  cnum: "",
  services: "",
  ...
})

const handleInputChange = e => setFields(f => ({...f, [e.target.name]: e.target.value}))

return (
    ...
    <input
      ref={Services.ref}
      type="text"
      value={fields.services}
      onChange={handleInputChange}
      placeholder={Services}
      name="services"
      id="Services"
    />
  )

推荐阅读