首页 > 解决方案 > 在 antd modal 中的 onclick 事件上调用自定义钩子 useApi 的正确方法

问题描述

我有一个想要拥有 CRUD 功能的应用程序。我创建了一个自定义钩子useAxios,我应该能够与所有 axios 方法一起使用:

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

export const useAxios = ({ url, method, body = null, headers = null }) => {
  const [response, setResponse] = useState([]);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(true);
  const fetchData = () => {
    axios[method](url, JSON.parse(headers), JSON.parse(body))
      .then((res) => {
        setResponse(res.data);
      })
      .catch((err) => {
        setError(err);
      })
      .finally(() => {
        setLoading(false);
      });
  };
  useEffect(() => {
    fetchData();
  }, [method, url, body, headers]);

  return { response, error, loading };
};

当我使用它来获取数据作为组件以这种方式加载时,这工作正常:

export default function Component({ useAxios }) {
  const { response, loading, error } = useAxios({
    method: "get",
    url: "http://localhost:4000/api/get",
    headers: JSON.stringify({ accept: "*/*" }),
  });
  return (...

但是我在 onClick 事件中使用它的 DELETE 方法时遇到了麻烦,例如:

// ... imports ...
import { Card, Col, Modal } from "antd";
const { confirm } = Modal;

export default function Item({ item }) {
  const { name, imageFileName, _id, description } = item ;

  function showDeleteConfirm() {
    confirm({
      title: "Are you sure delete this phone?",
      icon: <ExclamationCircleOutlined />,
      content: "The mobile market will suffer heavily for this action.",
      okText: "Yes",
      okType: "danger",
      cancelText: "No",
      onOk() {
       // HERE IS WHERE I WANT IT TO USE THE CUSTOM HOOK TO DELETE
      const { response, loading, error } = useAxios({
      method: "post",
      url: "http://localhost:4000/api/create",
      body: {
        name: "Item name",
        description: "Item description
      },
      headers: JSON.stringify({ accept: "*/*" }),
    });
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  }

  return (
    <Col>
      <Card
        hoverable
        style={{ width: 200 }}
        actions={[
          <DeleteOutlined key="delete" onClick={showDeleteConfirm} />,
        ]}
      >
      </Card>
    </Col>
  );
}

当我尝试调用该钩子时出现的错误是: React Hook “useAxios”在函数“onOk”中被调用,该函数既不是 React 函数组件也不是自定义 React Hook 函数。React 组件名称必须以大写字母开头

有没有一种方法可以在那里使用钩子,而不必直接在组件中进行 axios 调用?

标签: onclickmodal-dialoghookantd

解决方案


推荐阅读