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
相关产品推荐
相关产品推荐

