React中如何将表格选中行ID设为变量以实现编辑删除功能
解决表格行按钮无法获取对应ID的问题
核心问题是你的deletePet和updatePet函数无法访问当前行的pet变量,因为函数执行时的作用域和map循环里的作用域不共享。以下是两种直接有效的修改方案:
方案一:通过箭头函数传递参数
修改按钮的onClick事件,用箭头函数包裹并传入当前行的pet.id:
第一步:修改函数,接收ID参数
function deletePet(petId) { fetch(`http://localhost:3001/api?act=delete&id=${petId}`) .then(res => res.json()) .then(() => { fetchPets(); }) } function updatePet(petId) { // 若需要修改其他字段,也可以在这里传入pet的完整对象或对应字段 fetch(`http://localhost:3001/api?act=update&id=${petId}&animal=${name}&description=${desc}&age=${age}&price=${price}`) .then(res => res.json()) .then(() => { fetchPets(); }); }
第二步:更新按钮的点击事件
{pets.map(pet => ( <tr key={pet.id}> <td>{pet.animal}</td> <td>{pet.description}</td> <td>{pet.age}</td> <td>{pet.price}</td> <td> <Button variant="contained" onClick={() => updatePet(pet.id)}>Edit</Button> <Button variant="contained" onClick={() => deletePet(pet.id)}>Delete</Button> </td> </tr> ))}
方案二:使用bind绑定参数
如果偏好不用箭头函数,也可以用bind来绑定参数:
<Button variant="contained" onClick={updatePet.bind(null, pet.id)}>Edit</Button> <Button variant="contained" onClick={deletePet.bind(null, pet.id)}>Delete</Button>
函数的修改和方案一一致,需要接收petId参数。
为什么原来的方法无效?
你之前直接绑定onClick={deletePet}时,函数执行时的作用域里没有当前循环的pet变量,导致pet.id无法正确获取。箭头函数或bind会在循环时捕获当前的pet.id,确保函数执行时能拿到对应行的ID。
内容的提问来源于stack exchange,提问作者PrxPedro
相关产品推荐
相关产品推荐

