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
相关产品推荐
相关产品推荐

