You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Express+React中通过索引引用数组项实现删除功能

解决Express+React项目的删除功能问题

要实现点击删除按钮通过数组索引删除后端项目,需要分前端传参和后端处理两部分修改:


一、前端修改(Display.js + App.js)

1. 传递状态更新函数到Display组件

在App.js的Display组件props中添加updateState,确保删除后前端数据能同步更新:

// App.js 中Display组件部分
<Display 
  projectData={content.webProjects}
  updateState={updateState} // 新增该行
/>

2. 完善Display组件的删除逻辑

  • 让handleDelete接收当前项目的index参数
  • 将实际索引拼接到请求URL,替换占位符:index
  • 删除成功后调用updateState更新前端状态
  • 给Delete按钮绑定带当前索引的点击事件

修改后的Display.js:

import React from 'react'
import Card from 'react-bootstrap/Card';
import Button from 'react-bootstrap/Button';

const Display = ({projectData, updateState}) => { // 接收updateState
  const handleDelete = (index) => { // 接收索引参数
    fetch(`/api/${index}`, { // 拼接实际索引到URL
      method: "DELETE",
      headers: {
          "Content-Type": "application/json"
      }
    })
    .then((response) => response.json())
    .then((updatedData) => {
       updateState(updatedData); // 更新前端数据
       console.log("项目已删除", updatedData);
    })
    .catch(err => console.error("删除失败:", err));
  }

  return (
    <div className="flex flex-wrap displayCard justify-center">
        {projectData.map((project, index) => { // 变量名改为project避免重复
            return (
              <Card style={{ width: '18rem' }} key={index}>
                <Card.Body>
                  <Card.Title>{project.TITLE}</Card.Title>
                  <Card.Text>
                  Description: {project.DESCRIPTION}
                  </Card.Text>
                  <Card.Text>
                     URL: {project.URL}
                   </Card.Text>
                  <Card.Link ><Button>edit</Button></Card.Link>
                  <Card.Link >
                    <Button onClick={() => handleDelete(index)}>Delete</Button> {/* 绑定带索引的点击事件 */}
                  </Card.Link>
                </Card.Body>
              </Card>
            )
        })}
    </div>
  )
}

export default Display

二、后端修改(server.js)

添加DELETE路由,接收URL中的索引参数,验证合法性后删除数组元素,返回更新后的数组:

const express = require('express');
const app = express();
app.use(express.json()); // 解析JSON请求体

// 现有GET路由(若无则添加)
app.get('/api', (req, res) => {
  res.json({ webProjects });
});

// 新增DELETE路由
app.delete('/api/:index', (req, res) => {
  const index = parseInt(req.params.index); // 将URL参数转为数字
  // 验证索引是否合法
  if (index >= 0 && index < webProjects.length) {
    webProjects.splice(index, 1); // 删除对应索引的元素
    res.json({ webProjects }); // 返回更新后的数组
  } else {
    res.status(404).json({ message: "项目不存在" }); // 返回错误提示
  }
});

// 启动服务器(按实际端口调整)
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`服务器运行在端口 ${PORT}`));

关键说明

  • 前端通过URL参数传递索引,更符合RESTful设计规范
  • 后端必须将req.params.index转为数字,因为URL参数默认是字符串类型
  • 删除操作完成后返回更新后的数组,保证前后端数据同步
  • 增加索引合法性校验,避免因越界操作导致服务器报错

内容的提问来源于stack exchange,提问作者FreddyKruger75

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 14:55:04