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

ReactTable getTrProps处理嵌套数组时status未定义的错误修复

修复ReactTable读取status属性的未定义错误并实现已付款行高亮

问题说明

使用ReactTable展示嵌套结构的客户付款状态数组时,触发TypeError: Cannot read properties of undefined (reading 'status')错误,需求是将标记为Paid(已付款)的客户行高亮为黄色。

原始数据与代码

客户付款状态数据

[{
  "customers": {
      "_id": "63e9303a16267390f9304321",
      "customerdetails": "63e6a4d21aeb535a4fe1b841",
      "status": "Paid",
      "amountPaid": "500",
      "roomNo": "2",
      "servedby": "Wade Jones",
      "createdAt": "2023-02-12T18:30:18.756Z",
      "updatedAt": "2023-02-12T18:30:18.756Z",
      "__v": 0
   }
}]

出错的ReactTable代码

<ReactTable
  getTrProps = {(state, rowInfo, instance) => {
        if (rowInfo) {
          return {
            style: {
              background: rowInfo
                ? rowInfo.row.customers.status === 'Paid'
                  ? "Yellow"
                  : "none"
                : "none"
            }
          };
        }
        return {};
      }}
/>

修复方案

错误根源是部分行数据可能缺失customers对象,导致读取status时触发未定义错误。通过可选链操作符做安全取值,同时简化逻辑:

<ReactTable
  getTrProps={(state, rowInfo) => {
    if (!rowInfo) return {};
    
    // 安全判断层级属性,避免未定义错误
    const isPaid = rowInfo.row?.customers?.status === 'Paid';
    return {
      style: {
        background: isPaid ? 'yellow' : 'transparent'
      }
    };
  }}
/>

修复细节

  1. 可选链操作符?.:当rowInfo.row或rowInfo.row.customers不存在时,表达式直接返回undefined,不会抛出错误;
  2. 简化逻辑:将状态判断提取为变量isPaid,提升代码可读性;
  3. 标准CSS取值:用transparent替换none,更符合背景色的标准语义,效果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:05:17