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

React使用Grid组件时报TypeError: Cannot read property 'id' of undefined求助

报错原因

你遇到的TypeError: Cannot read property 'id' of undefined错误和Grid组件本身无关,问题出在AddTriggerButton组件读取this.state.props.record.id时,record属性为undefined。
react-admin 的Edit、SimpleForm组件只会把record等表单上下文属性注入到内置的输入、字段组件,你自定义的AddTriggerButton直接放在Grid内部,没有接收上层传递的record属性,自然读取不到对应的id字段。另外你在constructor里把props存入state的写法也有问题:props更新时state不会同步更新,后续可能出现数据不匹配的问题。

解决方法

方案1:使用react-admin提供的useRecordContext钩子(推荐,改成函数组件)

直接从表单上下文中获取record,无需手动传递属性:

import { useRecordContext } from 'react-admin';

const AddTriggerButton = () => {
  const record = useRecordContext();
  // 数据加载阶段record为空时先返回空,避免报错
  if (!record) return null;
  return (
    <div>
      <TriggerButton
        component={Link}
        to={{
          pathname: "/_triggers/create",
          data: { eid: record.id },
        }}
        startIcon={<AddIcon />}
      >
        新建触发器
      </TriggerButton>
    </div>
  );
};

方案2:保留类组件写法,手动传递record属性

首先修改SimpleForm的写法,拿到上下文的record后传递给自定义按钮:

<SimpleForm>
  {/* 从SimpleForm的render props中获取record */}
  {({ record }) => (
    <Grid container spacing={1} align="center">
      {/* 其余Grid内容保持不变 */}
      <Grid item sm={6}>
       <AddTriggerButton record={record} />
       <AddFieldButton record={record} />
      </Grid>
    </Grid>
  )}
</SimpleForm>

然后修改AddTriggerButton的代码,删除constructor中存props到state的逻辑,直接使用props并且加非空判断:

export default class AddTriggerButton extends React.Component {
  render() {
    // record为空时先返回空避免报错
    if (!this.props.record) return null;
    return (
      <div>
        <TriggerButton
          component={Link}
          to={{
            pathname: "/_triggers/create",
            data: { eid: this.props.record.id },
          }}
          startIcon={<AddIcon />}
        >
          新建触发器
        </TriggerButton>
      </div>
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 01:51:03