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

React嵌套对象遍历问题:无法在表格中正确渲染数据

问题分析与解决方案

核心问题

你在Tabledata组件中遍历social.value时,Object.keys(social.value).map((data, index) => {})里的data是对象的键名(比如email、facebook),并不是对应的值对象,所以data.notifications永远是undefined,导致图标无法正确渲染。

修复代码

修改Tabledata组件的遍历逻辑,改用Object.entries同时获取键名和对应的值对象:

function Tabledata({ social }) {
  console.log(social);

  return (
    <>
      <Table>
        <thead>
          <tr>
            <th>Communication channel</th>
            <th>Notifications</th>
          </tr>
        </thead>
        <tbody>
          {/* 用Object.entries获取[key, value]对 */}
          {Object.entries(social.value).map(([channel, details], index) => (
            <tr key={index}>
              <td>{channel}</td>
              <td>
                {details.notifications ? (
                  <CheckCircleIcon className="h-6 w-6 text-green-500" />
                ) : (
                  <XCircleIcon className="h-6 w-6 text-red-500" />
                )}
              </td>
            </tr>
          ))}
        </tbody>
      </Table>
    </>
  );
}

额外优化建议(若需支持修改通知状态)

如果要让通知开关可编辑并同步到Mantine Form,需要给每个notifications字段绑定表单输入:

// 需将form实例传递给Tabledata组件
function Tabledata({ social, form }) {
  return (
    <>
      <Table>
        <thead>
          <tr>
            <th>Communication channel</th>
            <th>Notifications</th>
          </tr>
        </thead>
        <tbody>
          {Object.entries(social.value).map(([channel, details], index) => {
            // 生成表单字段路径,比如social.email.notifications
            const fieldPath = `social.${channel}.notifications`;
            return (
              <tr key={index}>
                <td>{channel}</td>
                <td>
                  <Switch
                    {...form.getInputProps(fieldPath)}
                    checked={details.notifications}
                  />
                </td>
              </tr>
            );
          })}
        </tbody>
      </Table>
    </>
  );
}

// 在UserProfile组件中传递form
<Tabledata
  social={{ ...form.getInputProps("social") }}
  form={form}
  session={session}
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:41:12