React中调用DELETE REST API的异步remove方法点击无响应怎么解决?
问题根因
你的代码存在2个导致删除按钮点击无反应的问题:
- 事件名拼写错误:React的内置事件是驼峰命名规范,正确点击事件名为
onClick,你代码里写的是onCLick(第二个字母L大写,属于无效事件名,React不会识别该绑定,点击自然不会触发逻辑) - 类方法this指向丢失:你定义的
remove是普通类方法,直接在回调中调用this.remove时,this指向会丢失,即便事件触发也会抛出运行时报错。
修复步骤
- 先修正删除按钮的事件拼写,将
onCLick改为onClick - 修正
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
相关产品推荐
相关产品推荐

