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

如何在React+Redux项目中通过fetch DELETE请求删除数据

React Hooks + Redux 实现fetch DELETE请求删除数据方案

我在使用React Hooks和Redux开发时,尝试通过fetch的DELETE请求删除数据库中的数据/对象,期间遇到问题找不到解决方案。最终适配现有方案结合React Hooks和Redux技术栈,使用useDispatch替代了mapDispatchToProps完成功能实现,具体实现步骤如下:

1. 引入依赖

首先需要从react-redux引入useDispatch,从actions文件引入自定义删除函数:

import { deleteSet } from './Actions'
import { connect ,useDispatch} from 'react-redux';

2. 函数组件内声明dispatch

const dispatch = useDispatch();

3. 组件内调用删除方法

// take the id of the item/object you want to delete
const deleteItem = (item) => {
    const itemId = item._id
    console.log(itemId);
// use the dispatch you declared earlier with the function you import from Actions
    dispatch(deleteSet(itemId));
};

4. Actions文件删除逻辑实现

export const deleteSet = (id) => (dispatch) =>  {
    fetch(`/api/orders/${id}`, {
      method: "DELETE",
    })
    .then(response => response)
    .then(id => dispatch(
      {
        type: DELETE_ITEM,
        payload: deleteSet(id)
       }
      ))  
    }

5. Reducer对应处理逻辑

switch (action.type) {
        case DELETE_ITEM:
            return {item: action.payload};
        default:
           return state
    };

6. 后端server.js对应删除接口实现

app.delete("/api/orders/:id", async (req, res) => {
    const order = await Order.findByIdAndDelete(req.params.id);
    res.send(order)
})

希望上述内容能为你的开发提供帮助,如果有可优化的点欢迎在下方留言分享,祝编码愉快😊🤟

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 08:54:02