首页 > 解决方案 > 尝试使用 axios 和 React 钩子从 API 中删除

问题描述

您好,我正在尝试使用带有 ID 的输入从 API 中删除预订。显然有些不对劲。我试图将我的课程转换为 HOC,但我无法让它工作。现在我什至不能在文本框中输入。

我知道我有几个错误,但我不知道如何解决它们将不胜感激。HTML 中唯一相关的部分是表单。

    const DeleteBooking = () => {
  const [ModalIsOpen, SetModalIsOpen] = useState(false); // set false if closen when open
  const [booking, setDelete] = useState([]);

   const handleChange = (e) => {
    setDelete({ [e.target.name]: e.target.value });
  };

  useEffect((UserIdInput) => {
    const bookingId = UserIdInput.target.elements.bookingId.value;
    Axios.delete(`https://localhost:44366/api/Products/${bookingId}`) // change api key
      .then((response) => {
        console.log(response);
        setDelete(response.data);
      });
  }, []); 

  return (
    <>
      <div className="App-header">
        <button onClick={() => SetModalIsOpen(true)}>Radera bokning</button>
      </div>

      <Modal
        isOpen={ModalIsOpen}
        onRequestClose={() => SetModalIsOpen(false)}
        style={{
          overlay: {
            background:
              "linear-gradient(-500deg, #ee7752, #6e1b3b, #0c495f, #000000)",
          },
          content: {
            color: "black",
            textAlign: "center",
          },
        }}
      >
        <div>
          <h1>Radera Bokning</h1>
          <p style={{ marginTop: "20px" }}>
            Vänligen ange ditt bokningsNummer för att radera din bokning
          </p>

          <form onSubmit={() => setDelete}>
            <input
              onChange={handleChange}
              type="text"
              name=" bookingId"
              placeholder="BokningsID"
              value="bookingId"
            ></input>
            <button type="submit"></button>
          </form>

          <button
            style={{ marginTop: "100px" }}
            onClick={() => SetModalIsOpen(false)}
          >
            Tillbaka
          </button>
        </div>
      </Modal>
    </>
  );
};

export default DeleteBooking;

标签: reactjsaxiosreact-hooks

解决方案


这是一个非常简单的示例(工作沙箱),您可以在此基础上进行构建:

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

// => Component Code
// -> This component will be used to delete posts
export default function App() {
  // => State
  const [readPostId, writePostId] = useState("");
  const [readStatus, writeStatus] = useState("");
  // => Handlers
  const updatePostId = (e) => writePostId(e.target.value);
  const deletePost = async (e) => {
    e.preventDefault();
    try {
      await Axios.delete(`${API_ENDPOINT}/${readPostId}`);
      writeStatus("Post successfully deleted");
      setTimeout(() => writeStatus(""), 3000);
    } catch (err) {
      writeStatus("Post deletion failed");
    }
  };
  return (
    <div>
      <h1>Delete Posts Page</h1>
      <h2>Enter your Post ID:</h2>
      <em>Press 'Delete' without entering a number to cause an error</em>
      <form onSubmit={deletePost}>
        <input onChange={updatePostId} value={readPostId} />
        <input type="submit" value="Delete" />
      </form>
      {readStatus && <p>{readStatus}</p>}
    </div>
  );
}

// => Support Code
const API_ENDPOINT = "https://jsonplaceholder.typicode.com/posts";



推荐阅读