NextJS使用getStaticProps与getStaticPaths获取嵌套JSON数据不显示如何解决
问题根因
你接口返回的form_field_options是数组类型,并非普通对象,直接通过post.form_field_options.author_name取值相当于从数组实例上读取author_name属性,数组本身不存在该属性,所以返回undefined,不会触发报错但也没有内容显示。
解决方案
1. 快速修复(适合每个post的form_field_options固定只有1个元素的场景)
直接加数组下标配合可选链语法取值,避免空值报错:
// BlogHome组件里的作者名称读取 {post.form_field_options?.[0]?.author_name || ''} // [slug].js里的描述读取 {post.form_field_options?.[0]?.description || ''}
2. 预处理优化(减少组件重复取值逻辑)
在getStaticProps阶段提前拍平数据结构,避免组件里重复写嵌套路径:
// 修改[slug].js和index.js的getStaticProps里的数据处理逻辑 // 以[slug].js为例: export async function getStaticProps({params}) { const res = await fetch('http://localhost:8000/lasttwo/'); const posts = await res.json(); const rawPost = posts.find(post => post.slug === params.slug); // 提前拍平嵌套数组 const processedPost = { ...rawPost, formField: rawPost.form_field_options?.[0] || {} } return { props: { post: processedPost, } } }
处理后组件里直接取值即可:
{post.formField.author_name} {post.formField.description}
3. 通用DRY方案(适配任意嵌套层级,无需硬编码长路径)
封装通用嵌套取值工具函数,支持数组下标、对象属性混合的路径读取:
// 可以放在utils公共文件里全局复用 const getNestedValue = (obj, path, defaultValue = '') => { return path.reduce((acc, currKey) => { // 自动识别数字下标做类型转换 const key = /^\d+$/.test(currKey) ? Number(currKey) : currKey return acc?.[key] ?? defaultValue }, obj) }
使用时只需传入对应路径即可,适配所有嵌套字段读取:
// 读取作者名 {getNestedValue(post, ['form_field_options', '0', 'author_name'])} // 读取描述 {getNestedValue(post, ['form_field_options', '0', 'description'])} // 读取其他深层字段也可以直接传路径 {getNestedValue(post, ['other_nested_field', '2', 'child_attr'])}
4. 多元素适配方案(如果form_field_options可能返回多个值)
如果一个post对应多个作者/字段选项,直接遍历数组渲染即可:
{post.form_field_options?.map(option => ( <p key={option.id}>作者:{option.author_name}</p> )) || '暂无作者信息'}
内容的提问来源于stack exchange,提问作者Stackerme
相关产品推荐
相关产品推荐

