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

如何获取MUI X Data Grid checkboxSelection选中数据并存入变量跨页传递

问题原因及修复方案

核心问题点

  • 初始代码使用了已废弃的onSelectionChange事件,新版MUI X DataGrid的选择变更事件为onSelectionModelChange,所以最初的回调完全不会触发,导致没有console输出
  • React的setState是异步更新,执行setStudentsID后立即打印state,拿到的是更新前的旧值,会误以为赋值失败
  • 你后续更新的代码仅打印了选中数据,没有将其存入state,自然无法持久化存储后传递到其他页面
  • 多余的{...estudiantes}属性展开没有实际作用,可直接删除

修复步骤

1. 新增存储选中数据的状态

在组件内新增state存储选中的行完整数据:

const [selectedRows, setSelectedRows] = useState([]);

2. 修改DataGrid的选择回调逻辑

调整onSelectionModelChange的实现,把选中数据存入state:

<DataGrid
  rows={estudiantes}
  columns={columns}
  pageSize={5}
  rowsPerPageOptions={[5]}
  components={{
    Toolbar: CustomToolbar,
  }}
  checkboxSelection
  onSelectionModelChange={(newSelectionModel) => {
    // newSelectionModel为当前选中的所有行id数组
    const matchedRows = estudiantes.filter(row => newSelectionModel.includes(row.id));
    setSelectedRows(matchedRows);
    // 这里直接打印matchedRows即可拿到最新选中数据,不要打印selectedRows(异步更新有延迟)
    console.log('选中的学生数据:', matchedRows);
  }}
/>

3. 跳转页面传递数据

跳转时通过history.push的state参数携带选中数据:

const goToTargetPage = () => {
  history.push({
    pathname: '/你的目标页面路由',
    state: {
      selectedStudents: selectedRows
    }
  })
}

4. 目标页面接收数据

在目标页面用useLocation获取传递的选中数据:

import { useLocation } from 'react-router-dom';

function TargetPage() {
  const location = useLocation();
  // 取不到值时默认给空数组避免报错
  const selectedStudents = location.state?.selectedStudents || [];
  // 后续直接使用selectedStudents里的id、nombre等字段即可
}

注意事项

  • 需确保estudiantes数组中每一条数据都有唯一的id字段,和columns定义的field: 'id'对应,否则选择逻辑会匹配失败
  • 如果你的行id是字符串类型,匹配时不需要加toString(),只有id为数字类型且选择模型返回的是字符串id时才需要做类型转换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 13:24:03