You need to enable JavaScript to run this app. React中调用DELETE REST API的异步remove方法点击无响应怎么解决?
优惠活动
大模型
产品
解决方案
定价
更多

React中调用DELETE REST API的异步remove方法点击无响应怎么解决?

问题根因

你的代码存在2个导致删除按钮点击无反应的问题:

  • 事件名拼写错误:React的内置事件是驼峰命名规范,正确点击事件名为onClick,你代码里写的是onCLick(第二个字母L大写,属于无效事件名,React不会识别该绑定,点击自然不会触发逻辑)
  • 类方法this指向丢失:你定义的remove是普通类方法,直接在回调中调用this.remove时,this指向会丢失,即便事件触发也会抛出运行时报错。

修复步骤

  1. 先修正删除按钮的事件拼写,将onCLick改为onClick
  2. 修正remove方法的this指向,二选一即可:
    方案1:在constructor中手动绑定this
    在你的constructor代码块内加一行绑定逻辑:
constructor(props) {
    super(props)
    // 新增这一行绑定
    this.remove = this.remove.bind(this);
    this.state = {
        isLoading: false,
        Categories : [],
        Expenses : [],
        date : new Date(),
        item : this.emptyItem
    }
}

方案2:将remove方法改写为箭头函数,自动绑定this:

remove = async (id) => {
    await fetch(`/api/expenses/${id}` , {
        method: 'DELETE',
        headers: {
            'Accept' : 'application/json',
            'Content-Type' : 'application/json'
        }
    }).then(() => {
        let updatedExpenses = [...this.state.Expenses].filter(i => i.id !== id);
        this.setState({Expenses : updatedExpenses});
    });
}

完成以上两处修改后,点击删除按钮即可正常触发DELETE请求和列表更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 04:15:04