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

如何将深层嵌套数组转换为React-table的expanded初始状态所需对象

你可以通过递归遍历嵌套数据生成符合要求的展开状态结构,再配合localStorage做持久化即可实现刷新保留展开状态的需求,完整实现如下:

1. 生成初始展开状态

// 递归遍历嵌套行,生成路径状态对象
function generateExpandedState(rows, parentPath = '', result = {}) {
  rows.forEach((row, index) => {
    // 拼接当前层级的路径key
    const currentPath = parentPath ? `${parentPath}.${index}` : String(index);
    result[currentPath] = false; // 默认未展开
    // 存在子行则递归处理下一层
    if (Array.isArray(row.subRows) && row.subRows.length) {
      generateExpandedState(row.subRows, currentPath, result);
    }
  })
  return result;
}

// 测试数据调用示例
const data = [
  {
    "id": 1,
    "subRows": [
      {
        "id": 1,
        "subRows": [
          {
            "id": 1,
          }
        ]
      },
      {
        "id": 2,
        "subRows": [
          {
            "id": 4,
          }
        ]
      },
    ]
  },
  {
    "id": 55,
    "subRows": []
  }
];

// 生成的defaultExpanded就是符合react-table要求的初始结构
const defaultExpanded = generateExpandedState(data);

2. 结合localStorage做状态持久化

在react-table的配置逻辑中加入状态读写逻辑即可:

import { useTable, useExpanded } from 'react-table'
import { useEffect } from 'react'

function YourTable() {
  // 页面加载时优先读取本地存储的展开状态,无则用默认值
  const initialExpanded = JSON.parse(localStorage.getItem('tableExpandedState')) || defaultExpanded;

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
    state: { expanded }
  } = useTable(
    {
      columns,
      data,
      initialState: {
        expanded: initialExpanded
      }
    },
    useExpanded
  )

  // 监听展开状态变化,实时同步到localStorage
  useEffect(() => {
    localStorage.setItem('tableExpandedState', JSON.stringify(expanded))
  }, [expanded])

  // 其余表格渲染逻辑
  // ...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:36:03