Next.js+Strapi开发博客报错:读取Title时无法获取undefined属性
解决Next.js + Strapi博客map遍历时报错的问题
看起来你遇到的问题大概率是拼写错误导致的,我先帮你排查最明显的点:
1. 首要问题:属性名拼写错误
你在代码里写的是 post.attributtes.Title,但Strapi返回的标准字段名是 attributes(注意少了一个e!)。这个笔误会直接让JS找不到对应的属性,抛出Cannot read properties of undefined错误——因为post.attributtes本身就是undefined,自然无法读取Title。
2. 额外的严谨性优化
即使修正了拼写,也建议你做更安全的空值检查,避免个别文章数据结构异常的情况:
方案一:提前过滤无效数据
在map之前先过滤掉没有attributes的文章:
{posts && posts .filter(post => post?.attributes) // 过滤掉attributes不存在的项 .map((post: any, i: number) => { return ( <div key={i}> <h3>{post.attributes.Title}</h3> <h5>{post.attributes.H2}</h5> <p>{post.attributes.Description}</p> </div> ); })}
方案二:使用可选链操作符
用?.来安全访问嵌套属性,即使某个层级不存在也不会报错:
{posts && posts.map((post: any, i: number) => { return ( <div key={i}> <h3>{post.attributes?.Title || '暂无标题'}</h3> <h5>{post.attributes?.H2 || ''}</h5> <p>{post.attributes?.Description || ''}</p> </div> ); })}
3. 验证数据结构
你可以在getStaticProps里打印完整的返回数据,确认每个post项的结构是否符合预期:
export async function getStaticProps() { const res = await axios({ method: "get", url: "http://0.0.0.0:1337/api/posts", headers: { "Access-Control-Allow-Origin": "*", "Content-type": "application/json", "Access-Control-Allow-Methods": "POST, GET, PUT, DELETE, OPTIONS", "Access-Control-Allow-Headers": "Origin, Content-Type, X-Auth-Token", }, }); console.log('完整返回数据:', res.data); // 打印整个返回结构 const data = res.data; return { props: { posts: data.data, }, }; }
确保data.data里的每个元素都包含attributes对象,以及Title、H2、Description这些字段。
先修正拼写错误,应该就能解决大部分问题了,如果还有异常,再结合数据结构检查进一步排查。
内容的提问来源于stack exchange,提问作者Alberto Enríquez
相关产品推荐
相关产品推荐

