onclick - 在 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 调用?
解决方案
推荐阅读
- javascript - 执行以下步骤后,离子反应 android 将无法运行
- wso2 - 完成 wso2 mb 教程后无法运行 wso2 esb
- oracle - 如何使用 Oracle Integration Cloud (OIC) 从 Oracle Field Service Cloud (OFSC) 和 UPDATE Salesforce (SFDC) 获取更新的活动?
- sql - SQL Server 使用另一列的选定值用 AS 命名列
- c# - Entity Framework Core 3.0 对包含集合导航属性的性能影响(笛卡尔爆炸)
- reactjs - Google 结构化数据工具不读取我的 React 站点内容
- reactjs - react native - 将选项 allowNamespaces 传递给 babel typescript 插件
- sql - SQL Server 2014 - 查询以跳过行
- reactjs - 如何将自定义参数传递给 nextjs 动态路由,以便我可以在 getInitialProps 中访问它
- python - 如何清除 Apache 中的所有缓存?