![](/img/trans.png)
[英]How to delete a post using React Native and Axios and make fast refresh
[英]How to use a custom React hook to make a POST or DELETE request with Axios
我正在尝试在 React 中创建一个通用的 useAxios 钩子。 我希望能够将此钩子导入其他组件以发出获取、发布和删除请求。 我已经创建了钩子,它可以很好地发出 Get 请求,但我一直坚持如何使它适用于 Post/Delete 请求。
问题是当用户单击保存或删除按钮时我会发出发布/删除请求,但我无法从事件处理程序 function 或 useEffect 调用 React 挂钩。
下面是我创建的通用钩子:
import { useState, useEffect } from "react";
import axios from "axios";
export interface AxiosConfig<D> {
method?: 'get' | 'post' | 'delete' | 'put';
url: string;
data?: D;
params?: URLSearchParams;
}
export const useAxios = <T, D = undefined >(config: AxiosConfig<D>) => {
const [responseData, setResponseData] = useState<T>();
const [isLoading, setIsloading] = useState(true);
const [isError, setIsError] = useState(false);
useEffect(() => {
const controller = new AbortController();
const axiosRequest = async () => {
try {
const response = await axios({ ...config, signal: controller.signal })
setResponseData(response.data)
setIsloading(false);
} catch (error) {
setIsError(true);
setIsloading(false);
}
}
axiosRequest();
return () => {
controller.abort();
}
}, [config.url, config.method, config.data, config.params])
return {responseData, isLoading, isError}
}
这是我想发出删除请求的组件示例
import { useParams } from 'react-router';
import { useAxios } from '../../api/hooks/useAxios';
export interface IItem {
title: string;
info: string;
}
export default function Item() {
const { id } = useParams<{id?: string}>();
const {responseData: item, isLoading, isError} = useAxios<IItem>({
method: 'get',
url: `http://localhost:3000/items/${id}`
})
const handleDelete = () => {
//not sure what to do here. Need to make DELETE request
}
return (
<div>
{isLoading && <p className='loading'>Loading...</p>}
{isError && <p className='error'>Could Not Load Item</p>}
{item && (
<>
<h2>{item.title}</h2>
<p>{item.info}</p>
<button onClick={handleDelete}>Delete</button>
</>
)}
</div>
)
}
我可以直接在 Item 组件中发出 axios 请求,而不使用我的 useAxios 钩子,但我最终会在整个应用程序中重复代码。
假设您的DELETE
路由与GET
路由相同,您只需将方法类型存储在本地 state 变量中并更改它:
const { id } = useParams<{id?: string}>();
const [method, setMethod] = useState('get');
const {responseData: item, isLoading, isError} = useAxios<IItem>({
method,
url: `http://localhost:3000/items/${id}`
});
const handleDelete = () => setMethod('delete');
但是,我想您会意识到这只能解决部分问题,即您将组件的返回 JSX 与GET
请求的响应类型 ( IItem
) 紧密耦合在一起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.