所以我正在构建一个新的应用程序,并且想知道什么是文件/文件夹结构的最佳实践。我是否应该将所有处理 API 请求的函数聚合为以下代码:
import { useState, useEffect } from "react";
import axios from 'axios';
export function useLeads(){
const[leads,setLeads] = useState([]);
useEffect(() => {
fetchLeads();
}, []);
const fetchLeads = () => {
axios.get('http://localhost:5000/leads')
.then((res) => setLeads(res.data))
.catch((error) => console.error(error));
};
const addLead = (newLead) => {
axios.post('http://localhost:5000/leads/new', newLead)
.then(response => {
if (response.status === 200) {
setLeads([...leads, response.data])
} else {
throw new Error('Failed to add lead');
}
})
.catch(error => {
console.error(error);
});
}
const deleteLead = (name,email) => {
axios.delete(`http://localhost:5000/leads/delete?name=${name}&email=${email}`)
.then(response => {
if (response.status === 200) {
setLeads(leads.filter(lead => lead.name !== name && lead.email !== email));
}
})
.catch(error => {
console.error(error);
});
};
或者是否有更好的方法来做到这一点,例如在具有多个导出或每个请求的文件中的单独函数?
谢谢
我为我的
useAuth
包装纸使用了类似的挂钩结构。我认为您的设置不适合您的情况。例如,您不希望每次调用 useLeads()
时都获取所有线索。我将像这样的所有实用程序函数保存在 /src/lib
中的单独文件中,每个文件只有一个默认导出:
const addLead = (newLead) => {
axios.post('http://localhost:5000/leads/new', newLead)
.then(response => {
if (response.status === 200) {
setLeads([...leads, response.data])
} else {
throw new Error('Failed to add lead');
}
})
.catch(error => {
console.error(error);
});
}
export default addLead;
另外,不要在你的 fetch 函数中使用
useEffect()
。在您的组件脚本中使用它。
以下是您如何在实践中使用它的示例:
import React, { useEffect, useState } from "react";
import fetchLeads from "@/lib/fetchLeads";
export default function DisplayLeads() {
const [leads, setLeads] = useState();
useEffect(() => {
const thisFetchLeads = async () => {
const thisLeads = await fetchLeads();
if (typeof thisLeads === typeof {}) setLeads(thisLeads);
};
thisFetchLeads();
}, []);
return <div>{JSON.stringify(leads)}</div>;
}