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

React表格删除条目时点击事件循环触发、ID为undefined问题求助

问题原因

  • onClick事件绑定逻辑错误:你直接在onClick属性中执行了this.deleteC(data.idCars),组件渲染阶段就会立刻调用该方法,而非点击按钮时触发。若方法执行后触发组件重渲染,就会再次调用该方法,形成无限循环。
  • deleteC方法参数使用错误:方法定义时已经接收了idCars形参,但调用DataService.delete时错误传入了this.idCars,你既没有给组件实例的idCars赋值,state中存储的idCars默认为null,自然返回undefined。
  • 额外语法问题:当前代码把deleteC方法写在了constructor内部,不符合React类组件的写法规范,需要把deleteC方法移到constructor外面,和render方法平级。

修复方案

1. 修正deleteC方法定义

将方法移出constructor,同时修改内部传参:

constructor(props) {
  super(props);
  this.deleteC = this.deleteC.bind(this);
  this.state = {
    idCars: null,
    carName: "",
    carModel: "", 
    cars: [],
    submitted: false
  };
}
// 移到constructor外部
deleteC(idCars) {   
  DataService.delete(idCars)
    .then(response => {
      this.props.history.push('/Classement');
    })
    .catch(e => {
      console.log(e);
    });
}

2. 修改onClick绑定逻辑

用箭头函数包裹方法调用,保证只有点击按钮时才会触发执行:

<button className="btn btn-danger" onClick={() => this.deleteC(data.idCars)}>
  Remove
</button>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 08:15:05