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

如何通过Apollo Mutation获取待删除行ID以精准删除指定账户

解决React Table + GraphQL删除时无法获取目标账户ID的问题

你遇到的问题其实很直观:你的DeleteAccount组件根本不知道要删除哪一行,因为你没有把当前行的账户ID传递给它。下面是一步步的修复方案:

1. 从React Table传递当前行的账户ID给删除组件

在ShowAccount.js里,React Table的SubComponent可以拿到当前行的row对象,其中row.original就是该行对应的账户数据(包含id字段)。我们只需要把这个id作为props传给DeleteAccountWithData:

// ShowAccount.js 里的SubComponent部分
SubComponent={row =>
  <div style={{ padding: '10px' }}>
    {/* 把当前行的账户ID传递给删除组件 */}
    <DeleteAccountWithData accountId={row.original.id} />
  </div>
}

2. 在DeleteAccount组件中使用传递过来的ID执行mutation

现在DeleteAccount组件可以通过props拿到accountId了,把原来硬编码的id: 2替换成动态的this.props.accountId即可:

// DeleteAccount.js 里的onDeleteAccount方法
onDeleteAccount = () => {
  this.props
    .mutate({
      refetchQueries: [{ query: queryAccountList }],
      variables: { 
        id: this.props.accountId // 这里用传递过来的动态ID
      },
    })
    .then(({ data }) => {
      console.log('mutation deleteAccount: SUCCESS', data);
    })
    .catch(error => {
      console.log('mutation deleteAccount: ERROR', error);
    });
}

额外优化(可选)

如果你的DeleteAccount组件不需要维护自己的state,可以删掉冗余的构造函数,让代码更简洁:

// DeleteAccount.js 简化后的组件
class DeleteAccount extends React.Component {
  onDeleteAccount = () => {
    // 同上的mutation代码
  }

  render() {
    return (
      <div>
        <button onClick={this.onDeleteAccount}>Delete</button>
      </div>
    );
  }
}

这样修改后,每一行的删除按钮都会绑定当前行的账户ID,点击时就能精准删除对应的账户了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:03:46