【发布时间】:2021-01-20 15:54:41
【问题描述】:
我正在复制/粘贴相同的代码以在多个组件中发出 axios 请求,如下所示:
React.useEffect(() => {
axios
.get<IDownloads[]>(`${process.env.PUBLIC_URL}/api/downloads`, {
headers: {
'Content-Type': 'application/json',
},
timeout: 5000,
})
.then((response) => {
setFaqs(response.data);
})
.catch((ex) => {
const err = axios.isCancel(ex)
? 'Request cancelled'
: ex.code === 'ECONNABORTED'
? 'A timeout has occurred'
: ex.response.status === 404
? 'Resource not found'
: 'An unexpected error has occurred';
setError(err);
});
}, []);
有效,但不遵循 DRY。我希望能够在我的应用程序的其他区域重用此代码,但需要能够更改 .get${process.env.PUBLIC_URL}/api/downloads 以在其他区域工作。例如 .get
export default function useApiRequest<T>(url: string): { response: T | null; error: Error | null} {
const [response, setResponse] = React.useState<T | null>(null);
const [error, setError] = React.useState<Error | null>(null);
React.useEffect(() => {
const fetchData = async (): Promise<void> => {
try {
const res = await axios(`${process.env.PUBLIC_URL}${url}`);
setResponse(res.data);
} catch (error) {
setError(error);
}
};
fetchData();
}, [url]);
return { response, error };
};
并像这样在这个组件中使用它:
interface IDownloads {
db_id: number;
file_description: string;
file_name: string;
developer_name: string;
date_uploaded: string;
file_url: string;
}
const defaultProps: IDownloads[] = [];
const DownloadCodeSamplesPage: React.FC = () => {
const downloadQuery = useApiRequest<IDownloads[]>('/api/download');
const [downloads, setDownloads]: [IDownloads[], (posts: IDownloads[]) => void] =
React.useState(defaultProps);
在我返回时,我正在像这样映射下载
downloads.map((download) => (
<tr key={download.db_id}>
<td>{download.file_description}</td>
<td>{download.file_name}</td>
<td>{download.developer_name}</td>
<td>{download.date_uploaded}</td>
当我运行程序时,我没有收到来自 api 调用的任何数据。我做错了什么?
【问题讨论】:
标签: reactjs typescript axios refactoring dry