Next.js中如何展示嵌套数组?解决接口返回对象的渲染问题
问题解决:Next.js组件无法展示嵌套数组数据
待展示的JSON数据
{"count": 2,"rows": [{"id": "5ab46e31-391c-46a7-8e45-db9ada07626d","name": "admin","email": "admin@gmail.com","phoneNumber": "95397454542325","username": "admin","password": "$2b$10$esLfedWAPEMAgWJ5HBAFQu6u47Cbfep7hnUTDZPswb4gWFhZW0rbm","role": "admin","isActive": true,"createdAt": "2023-09-29T11:00:55.388Z","updatedAt": "2023-09-29T11:00:55.388Z"},{"id": "58aacbcd-2344-40f1-a9e9-11c70d44cbb4","name": "Aman","email": "aman2000@gmail.com","phoneNumber": "8304893218","username": "Aman-admin","password": "$2b$10$uZZrRz5bATzJ3jPCAURpKeEP/TaHhoWhmKUvWSyIrOvKMmD3yNuKi","role": "user","isActive": true,"createdAt": "2023-10-07T09:58:51.193Z","updatedAt": "2023-10-07T10:00:31.590Z"}]}
原Next.js前端代码
'use client' import React from 'react'; const plans = async () => { const res = await fetch('http://localhost:3001/api/plans', { cache: 'no-store' }); // fetch gives a promise, so use const res = await console.log(res);//table table-zebra absolute top-24 left-40 const users = await res.json(); return ( <div> <button className='bg-sky-600 text-black p-2 rounded-lg absolute top-4 right-40 hover:text-white transition-colors'>Create plans</button> <h1 className='absolute top-14 left-40'>Plans</h1> <div> <table className='table-column-group absolute top-24 left-40 min-w-full divide-y divide-gray-200 border'> <thead> <tr> <th>Name</th> <th>Email</th> </tr> </thead> <tbody> {users.map((data) => ( <tr key={data.id}> <td>{data.name}</td> <td>{data.email}</td> </tr>your text ))} </tbody> </table> </div> </div> ); }; export default plans;
问题分析与修改方案
原代码的核心问题是:接口返回的JSON是包含count和rows属性的对象,而非直接的数组。原代码直接对整个users对象调用map方法,会触发语法错误(对象没有map方法),导致数据无法展示。
需要做两处关键修改:
- 提取
users.rows作为要遍历的数组,而非使用整个users对象 - 移除JSX代码中多余的
your text字符串,避免语法错误
修改后的完整代码
'use client' import React from 'react'; const plans = async () => { const res = await fetch('http://localhost:3001/api/plans', { cache: 'no-store' }); console.log(res); const users = await res.json(); // 提取嵌套在rows中的用户数据数组 const userList = users.rows; return ( <div> <button className='bg-sky-600 text-black p-2 rounded-lg absolute top-4 right-40 hover:text-white transition-colors'>Create plans</button> <h1 className='absolute top-14 left-40'>Plans</h1> <div> <table className='table-column-group absolute top-24 left-40 min-w-full divide-y divide-gray-200 border'> <thead> <tr> <th>Name</th> <th>Email</th> </tr> </thead> <tbody> {userList.map((data) => ( <tr key={data.id}> <td>{data.name}</td> <td>{data.email}</td> </tr> ))} </tbody> </table> </div> </div> ); }; export default plans;
额外优化建议
- 可以添加数据加载状态处理,比如在请求完成前展示加载提示
- 增加错误处理逻辑,比如判断
res.ok,若请求失败则给出友好提示
内容的提问来源于stack exchange,提问作者Ashhad Biju
相关产品推荐
相关产品推荐

