如何使用React Hooks执行更新逻辑?

发布于 2025-01-22 08:20:26 字数 10359 浏览 4 评论 0原文

因此,在这种情况下,当用户单击数据库表上的编辑链接时,它们会重定向到更新表格,但是数据不会在注册表单上呈现。我希望该objectID中的参数能够在输入字段上渲染,因此,当单击“更新”按钮时,将在服务器中修改数据。此外,控制台的消息意味着在手动填写该表格时已成功的证券请求。怎么了?

数据库表代码:

const Admin = () => {
  const [tabulate, setTabulate] = useState([]);
  const getRequest = async () => {
    try {
      const res = await axios.get("http://localhost:8080/register");
      console.log(res.statusText);
      setTabulate(res.data);
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    getRequest();
  }, []);

  const handleDelete = (_id) => {
    axios
      .delete("http://localhost:8080/register/" + _id)
      .then((res) => {
        console.log(res.statusText);
        getRequest();
      })
      .catch((err) => {
        console.log(err);
      });
  };

  return (
    <div className="page-wrapper">
      <h3>Database Administrator</h3>
      <Table striped bordered hover className="data-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Business Name</th>
            <th>Address</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Category</th>
            <th>Edit</th>
            <th>Delete</th>
          </tr>
        </thead>
        <tbody>
          {tabulate.map((item) => (
            <tr key={item._id}>
              <td>{item.ID}</td>
              <td>{item.firstName}</td>
              <td>{item.lastName}</td>
              <td>{item.businessName}</td>
              <td>{item.address}</td>
              <td>{item.email}</td>
              <td>{item.businessPhone}</td>
              <td>{item.category}</td>
              <td>
                <Button
                  bg="success"
                  variant="dark"
                  style={{
                    color: "white",
                    marginLeft: "0px",
                    fontSize: "10px",
                  }}
                >
                  <Link to={`/edit-vendor/${item._id}`} className="links">
                    Edit
                  </Link>
                  <Routes>
                    <Route
                      path="/edit-vendor/:ID"
                      element={<EditVendor />}
                    />
                  </Routes>
                </Button>
              </td>
              <td>
                <Button
                  bg="danger"
                  variant="dark"
                  size="sm"
                  style={{
                    color: "white",
                    marginLeft: "0px",
                    fontSize: "10px",
                  }}
                  onClick={(e) => handleDelete(item._id)}
                >
                  Delete
                </Button>
              </td>
            </tr>
          ))}
        </tbody>
      </Table>
    </div>
  );
};

带有ObjectID的链接元素将用户重定向到更新表单。

更新表格:

const EditVendor = () => {
  let navigate = useNavigate();
  const params = useParams();

  const [ID, setVendorID] = useState(0);
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [businessName, setBusinessName] = useState("");
  const [address, setAddress] = useState("");
  const [email, setEmail] = useState("");
  const [businessPhone, setBusinessPhone] = useState(0);
  const [category, setCategory] = useState("");
  const [photos, setPhotos] = useState("");

  useEffect(() => {
    axios
      .get(`http://localhost:8080/register/`, {ID: params.ID})
      .then((res) => {
        const vendorData = res.data;
        console.log(vendorData);
        setVendorID(vendorData.ID);
        setFirstName(vendorData.firstName);
        setLastName(vendorData.lastName);
        setBusinessName(vendorData.businessName);
        setAddress(vendorData.address);
        setEmail(vendorData.email);
        setBusinessPhone(vendorData.businessPhone);
        setCategory(vendorData.category);
        setPhotos(vendorData.photos);
      })
      .catch((err) => {
        console.log(err);
      });
  }, [params.ID]);

  const handleUpdate = (id, e) => {
    e.preventDefault();
    axios
      .put(`http://localhost:8080/register/${ID}`, {
        ID,
        firstName,
        lastName,
        businessName,
        address,
        email,
        businessPhone,
        category,
        photos,
      })
      .then((res) => {
        console.log(res.data);
        navigate("/admin");
      })
      .catch((err) => {
        console.log(err);
      });
  };

  return (
    <div
      className="page-wrapper-form"
      onSubmit={(ID, e) => handleUpdate(ID, e)}
    >
      <form className="update-form" encType="multipart/form-data">
        <h3>Update Form (Admin)</h3>
        <label htmlFor="vendorID">Your ID:</label>
        <input
          type="number"
          id="ID"
          name="ID"
          // disabled
          value={ID}
          onChange={(e) => {
            setVendorID(e.target.value);
          }}
          style={{ backgroundColor: "gray", color: "white" }}
        />
        <label htmlFor="firstName">First Name:</label>
        <input
          type="text"
          id="firstName"
          name="firstName"
          minLength={1}
          maxLength={50}
          spellCheck="false"
          autoCapitalize="on"
          value={firstName}
          onChange={(e) => {
            setFirstName(e.target.value);
          }}
        />
        <label htmlFor="lastname">Last Name:</label>
        <input
          type="text"
          id="lastName"
          name="lastName"
          minLength={1}
          maxLength={50}
          spellCheck="false"
          autoCapitalize="on"
          value={lastName}
          onChange={(e) => {
            setLastName(e.target.value);
          }}
        />
        <label htmlFor="businessname">Business Name:</label>
        <input
          type="text"
          id="businessName"
          name="businessName"
          minLength={1}
          maxLength={50}
          spellCheck="false"
          autoCapitalize="on"
          value={businessName}
          onChange={(e) => {
            setBusinessName(e.target.value);
          }}
        />
        <label htmlFor="address">Address:</label>
        <input
          type="text"
          id="address"
          name="address"
          minLength={1}
          maxLength={50}
          spellCheck="false"
          autoCapitalize="on"
          value={address}
          onChange={(e) => {
            setAddress(e.target.value);
          }}
        />
        <label htmlFor="email">Email:</label>
        <input
          type="text"
          id="email"
          name="email"
          minLength={1}
          maxLength={50}
          spellCheck="false"
          value={email}
          onChange={(e) => {
            setEmail(e.target.value);
          }}
        />
        <label htmlFor="businessPhone">Business Phone:</label>
        <input
          type="tel"
          id="businessPhone"
          name="businessPhone"
          size={11}
          value={businessPhone}
          onChange={(e) => {
            setBusinessPhone(e.target.value);
          }}
        />
        <label htmlFor="category">Category:</label>
        <select
          id="category"
          value={category}
          onChange={(e) => {
            setCategory(e.target.value);
          }}
        >
          <option value="No selection" name="No Selection">
            --Select--
          </option>
          <option value="Okirika" name="Okrika">
            Okirika
          </option>
          <option value="Fabrics" name="Fabrics">
            Fabrics
          </option>
          <option value="Provisions" name="Provisions">
            Provisions
          </option>
          <option
            value="Computers and accessories"
            name="Computers and accessories"
          >
            Computers and accessories
          </option>
          <option value="Spare parts" name="Spare parts">
            Spare parts
          </option>
          <option value="Foodstuff" name="Foodstuff">
            Foodstuff
          </option>
          <option value="Leather goods" name="Leather goods">
            Leather goods
          </option>
          <option value="Building materials" name="Building materials">
            Building materials
          </option>
          <option value="Vehicles" name="Vehicles">
            Vehicles
          </option>
        </select>
        <label htmlFor="photos">Upload photos:</label>
        <span
          style={{ color: "tomato", fontSize: "0.7rem", marginLeft: "56px" }}
        >
          (Only JPG/JPEG and PNG are accepted.)
        </span>
        <input
          type="text"
          className="photos"
          name="photos"
          value={photos}
          onChange={(e) => {
            setPhotos(e.target.value);
          }}
        />
        <button type="submit" id="update-btn">
          Submit
        </button>
      </form>
    </div>
  );
};

预计该表的数据将在此表单的输入字段上渲染,但这不起作用。

然后,这就是后端代码的外观。

后端代码:

exports.update = (req, res) => {
  const id = req.params._id;

  Registered.findByIdAndUpdate(id, { $set: req.body }, (err, data, next) => {
    if (err) {
      console.log(err);
      return next(err);
    } else {
      res.status(200).json(data);
      console.log(
        `Vendor information was updated successfully!`
      );
    }
  });
};

So, in this case, when the user clicks an edit link on the database table, they are redirected to an update form, but the data does not render on the registration form. I expect the parameters within that objectID to render on the input fields, so that when the update button is clicked, the data is modified in the server. Also, the console message implies that a successful PUT request has been made when that form is filled manually. What could be wrong?

Database table code:

const Admin = () => {
  const [tabulate, setTabulate] = useState([]);
  const getRequest = async () => {
    try {
      const res = await axios.get("http://localhost:8080/register");
      console.log(res.statusText);
      setTabulate(res.data);
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    getRequest();
  }, []);

  const handleDelete = (_id) => {
    axios
      .delete("http://localhost:8080/register/" + _id)
      .then((res) => {
        console.log(res.statusText);
        getRequest();
      })
      .catch((err) => {
        console.log(err);
      });
  };

  return (
    <div className="page-wrapper">
      <h3>Database Administrator</h3>
      <Table striped bordered hover className="data-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Business Name</th>
            <th>Address</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Category</th>
            <th>Edit</th>
            <th>Delete</th>
          </tr>
        </thead>
        <tbody>
          {tabulate.map((item) => (
            <tr key={item._id}>
              <td>{item.ID}</td>
              <td>{item.firstName}</td>
              <td>{item.lastName}</td>
              <td>{item.businessName}</td>
              <td>{item.address}</td>
              <td>{item.email}</td>
              <td>{item.businessPhone}</td>
              <td>{item.category}</td>
              <td>
                <Button
                  bg="success"
                  variant="dark"
                  style={{
                    color: "white",
                    marginLeft: "0px",
                    fontSize: "10px",
                  }}
                >
                  <Link to={`/edit-vendor/${item._id}`} className="links">
                    Edit
                  </Link>
                  <Routes>
                    <Route
                      path="/edit-vendor/:ID"
                      element={<EditVendor />}
                    />
                  </Routes>
                </Button>
              </td>
              <td>
                <Button
                  bg="danger"
                  variant="dark"
                  size="sm"
                  style={{
                    color: "white",
                    marginLeft: "0px",
                    fontSize: "10px",
                  }}
                  onClick={(e) => handleDelete(item._id)}
                >
                  Delete
                </Button>
              </td>
            </tr>
          ))}
        </tbody>
      </Table>
    </div>
  );
};

The Link element with an objectID redirects the user to the update form.

Update form:

const EditVendor = () => {
  let navigate = useNavigate();
  const params = useParams();

  const [ID, setVendorID] = useState(0);
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [businessName, setBusinessName] = useState("");
  const [address, setAddress] = useState("");
  const [email, setEmail] = useState("");
  const [businessPhone, setBusinessPhone] = useState(0);
  const [category, setCategory] = useState("");
  const [photos, setPhotos] = useState("");

  useEffect(() => {
    axios
      .get(`http://localhost:8080/register/`, {ID: params.ID})
      .then((res) => {
        const vendorData = res.data;
        console.log(vendorData);
        setVendorID(vendorData.ID);
        setFirstName(vendorData.firstName);
        setLastName(vendorData.lastName);
        setBusinessName(vendorData.businessName);
        setAddress(vendorData.address);
        setEmail(vendorData.email);
        setBusinessPhone(vendorData.businessPhone);
        setCategory(vendorData.category);
        setPhotos(vendorData.photos);
      })
      .catch((err) => {
        console.log(err);
      });
  }, [params.ID]);

  const handleUpdate = (id, e) => {
    e.preventDefault();
    axios
      .put(`http://localhost:8080/register/${ID}`, {
        ID,
        firstName,
        lastName,
        businessName,
        address,
        email,
        businessPhone,
        category,
        photos,
      })
      .then((res) => {
        console.log(res.data);
        navigate("/admin");
      })
      .catch((err) => {
        console.log(err);
      });
  };

  return (
    <div
      className="page-wrapper-form"
      onSubmit={(ID, e) => handleUpdate(ID, e)}
    >
      <form className="update-form" encType="multipart/form-data">
        <h3>Update Form (Admin)</h3>
        <label htmlFor="vendorID">Your ID:</label>
        <input
          type="number"
          id="ID"
          name="ID"
          // disabled
          value={ID}
          onChange={(e) => {
            setVendorID(e.target.value);
          }}
          style={{ backgroundColor: "gray", color: "white" }}
        />
        <label htmlFor="firstName">First Name:</label>
        <input
          type="text"
          id="firstName"
          name="firstName"
          minLength={1}
          maxLength={50}
          spellCheck="false"
          autoCapitalize="on"
          value={firstName}
          onChange={(e) => {
            setFirstName(e.target.value);
          }}
        />
        <label htmlFor="lastname">Last Name:</label>
        <input
          type="text"
          id="lastName"
          name="lastName"
          minLength={1}
          maxLength={50}
          spellCheck="false"
          autoCapitalize="on"
          value={lastName}
          onChange={(e) => {
            setLastName(e.target.value);
          }}
        />
        <label htmlFor="businessname">Business Name:</label>
        <input
          type="text"
          id="businessName"
          name="businessName"
          minLength={1}
          maxLength={50}
          spellCheck="false"
          autoCapitalize="on"
          value={businessName}
          onChange={(e) => {
            setBusinessName(e.target.value);
          }}
        />
        <label htmlFor="address">Address:</label>
        <input
          type="text"
          id="address"
          name="address"
          minLength={1}
          maxLength={50}
          spellCheck="false"
          autoCapitalize="on"
          value={address}
          onChange={(e) => {
            setAddress(e.target.value);
          }}
        />
        <label htmlFor="email">Email:</label>
        <input
          type="text"
          id="email"
          name="email"
          minLength={1}
          maxLength={50}
          spellCheck="false"
          value={email}
          onChange={(e) => {
            setEmail(e.target.value);
          }}
        />
        <label htmlFor="businessPhone">Business Phone:</label>
        <input
          type="tel"
          id="businessPhone"
          name="businessPhone"
          size={11}
          value={businessPhone}
          onChange={(e) => {
            setBusinessPhone(e.target.value);
          }}
        />
        <label htmlFor="category">Category:</label>
        <select
          id="category"
          value={category}
          onChange={(e) => {
            setCategory(e.target.value);
          }}
        >
          <option value="No selection" name="No Selection">
            --Select--
          </option>
          <option value="Okirika" name="Okrika">
            Okirika
          </option>
          <option value="Fabrics" name="Fabrics">
            Fabrics
          </option>
          <option value="Provisions" name="Provisions">
            Provisions
          </option>
          <option
            value="Computers and accessories"
            name="Computers and accessories"
          >
            Computers and accessories
          </option>
          <option value="Spare parts" name="Spare parts">
            Spare parts
          </option>
          <option value="Foodstuff" name="Foodstuff">
            Foodstuff
          </option>
          <option value="Leather goods" name="Leather goods">
            Leather goods
          </option>
          <option value="Building materials" name="Building materials">
            Building materials
          </option>
          <option value="Vehicles" name="Vehicles">
            Vehicles
          </option>
        </select>
        <label htmlFor="photos">Upload photos:</label>
        <span
          style={{ color: "tomato", fontSize: "0.7rem", marginLeft: "56px" }}
        >
          (Only JPG/JPEG and PNG are accepted.)
        </span>
        <input
          type="text"
          className="photos"
          name="photos"
          value={photos}
          onChange={(e) => {
            setPhotos(e.target.value);
          }}
        />
        <button type="submit" id="update-btn">
          Submit
        </button>
      </form>
    </div>
  );
};

It is expected that the data from the table will be rendered on the input fields in this form, but that does not work.

Then, this is how the backend code looks.

Backend code:

exports.update = (req, res) => {
  const id = req.params._id;

  Registered.findByIdAndUpdate(id, { $set: req.body }, (err, data, next) => {
    if (err) {
      console.log(err);
      return next(err);
    } else {
      res.status(200).json(data);
      console.log(
        `Vendor information was updated successfully!`
      );
    }
  });
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文