我正在使用 React 开发一个 Web 应用程序,其中有一个显示客户端列表的表格。在客户端上执行 CRUD 操作后,该表应自动更新。但是,我遇到了一个特定问题:添加或删除客户端后,表不会自动更新。仅当我编辑现有客户端时它才能正常工作。为了使其他方法发挥作用,我必须离开该页面并返回该部分。
正如我提到的,请求到达 API 并返回预期信息,但更新表失败,即使该方法理论上已实现。
这是我的代码:
const loadClients = async () => {
try {
const clientsData = await salesApi.getClients();
const sortedClients = clientsData.sort((a, b) => a.id - b.id);
setClients(sortedClients);
} catch (error) {
console.error('Error fetching clients:', error);
}
};
const handleEditClick = (client) => {
setEditingClient(client);
};
const handleCancelEdit = () => {
setEditingClient(null);
};
const handleClientSubmit = async (formData) => {
try {
await salesApi.addClient({
firstName: formData.firstName,
secondName: formData.secondName,
firstLastName: formData.firstLastName,
secondLastName: formData.secondLastName,
identificationNumber: formData.identificationNumber,
isCreditCandidate: formData.isCreditCandidate,
});
console.log('Client successfully registered:', formData);
loadClients();
} catch (error) {
console.error('Error adding client:', error.message);
}
};
const handleSaveEdit = async (editedClient) => {
try {
console.log('Data to send to server:', editedClient);
await salesApi.updateClient(editedClient);
console.log('Client successfully updated:', editedClient);
loadClients();
} catch (error) {
console.error('Error updating client:', error);
}
};
const handleDeleteClient = async (clientId) => {
try {
console.log('Attempting to delete client with ID:', clientId);
const response = await salesApi.deleteClient(clientId);
console.log('Delete response:', response);
if (response.status === 200) {
console.log('Client successfully deleted:', clientId);
loadClients();
} else {
console.error('Error deleting client:', response.statusText);
}
} catch (error) {
console.error('Error deleting client:', error);
}
};
return (
<MainPageContainer>
<h1>Clients</h1>
{(editingClient || !editingClient) && (
<ClientsRegistration
onSubmit={(formData) => {
if (editingClient) {
handleSaveEdit({ ...editingClient, ...formData });
} else {
handleClientSubmit(formData);
}
}}
onCancel={handleCancelEdit}
/>
)}
<ClientsTable
clients={clients}
onEditClick={handleEditClick}
onDeleteClick={handleDeleteClient}
handleSaveEdit={handleSaveEdit}
/>
</MainPageContainer>
);
};
任何有关如何解决此问题的建议或帮助将不胜感激。
确保在获取删除或更新 api 时重新获取表的获取查询,以便新值可以在表中替换