React+Express项目删除功能异常:前端报错、新增项404求助
React+Express 删除功能问题修复方案
问题1:点击删除后出现“无法读取undefined的map属性”错误
原因:删除后更新state时格式不匹配,App组件中content的结构是{webProjects: 项目数组},但TableData中调用setContent({ projectData: updatedProjects })会将content改为{projectData: ...},导致content.webProjects变为undefined,表格渲染时projectData.map报错。
修复:修改TableData中deleteItem函数的setContent调用,保持结构一致:
// TableData.js 中的 deleteItem 函数 const deleteItem = (projectId) => { fetch("/api/delete", { method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: projectId }) }) .then((response) => response.json()) .then((updatedProjects) => { // 改为匹配 App 中 content 的结构 setContent({ webProjects: updatedProjects }); }) }
问题2:新增项目点击删除返回404 Not Found
原因有两点:
- 新增项目的ID为字符串类型,后端delete接口用
parseInt(req.body.id)转为数字,两者类型不匹配导致找不到项目; - 后端delete接口返回格式与其他接口不一致(直接返回数组而非
{webProjects: 数组}),可能导致前端state更新异常。
修复步骤:
步骤1:统一新增项目的ID类型(转为数字)
修改server.js中的post接口,将ID转为数字:
// server.js 的 /api/create 接口 app.post("/api/create", (req, res) => { newObj = { ID: parseInt(req.body.ID), // 转为数字类型 TITLE: req.body.TITLE, DESCRIPTION: req.body.DESCRIPTION, URL: req.body.URL, }; webProjects.push(newObj); res.json({ webProjects }); })
步骤2:统一后端delete接口的返回格式
修改server.js中的delete接口,返回与其他接口一致的结构:
// server.js 的 /api/delete 接口 app.delete("/api/delete", (req, res) => { const projectId = parseInt(req.body.id); const projectIndex = webProjects.findIndex(project => project.ID === projectId); if (projectIndex === -1) { return res.status(404).json({ msg: "Project not found" }); } webProjects.splice(projectIndex, 1); // 返回与其他接口一致的结构 res.json({ webProjects }); })
步骤3:优化前端错误处理(可选但推荐)
在TableData的deleteItem中添加错误处理,避免请求失败时阻塞流程:
const deleteItem = (projectId) => { fetch("/api/delete", { method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: projectId }) }) .then((response) => { if (!response.ok) { throw new Error(`请求失败:${response.status}`); } return response.json(); }) .then((updatedData) => { // 此时updatedData是{webProjects: ...},直接传入setContent即可 setContent(updatedData); }) .catch((error) => { console.error("删除失败:", error); // 可添加用户提示,比如alert(error.message) }) }
内容的提问来源于stack exchange,提问作者FreddyKruger75
相关产品推荐
相关产品推荐

