Next.js调用GraphCMS获取数据成功但页面空白无法渲染排查
Next.js + GraphCMS 博客本地白屏问题修复
接口可正常返回数据但页面空白,均为前端代码的语法、逻辑错误,按以下点逐一修复即可:
1. 首页map遍历未返回渲染组件(白屏核心原因)
pages/index.js中调用posts.map时,回调函数使用大括号包裹内容,但没有写return返回BlogPost组件,相当于遍历完成后没有任何内容被渲染到页面上。
- 错误代码片段:
{posts.map((post) => { <BlogPost title={post.title} author={post.author} slug={post.slug} coverImage={post.coverImage} date={post.date} />; })}
- 修复方案:两种写法二选一即可,注意循环渲染必须给组件加唯一
key属性(用接口返回的post.id即可,避免控制台抛警告)
// 写法1:大括号内加return {posts.map((post) => { return <BlogPost key={post.id} title={post.title} author={post.author} slug={post.slug} coverImage={post.coverImage} date={post.date} /> })} // 写法2:用圆括号替代大括号,隐式返回组件(更简洁) {posts.map((post) => ( <BlogPost key={post.id} title={post.title} author={post.author} slug={post.slug} coverImage={post.coverImage} date={post.date} /> ))}
2. 文章链接模板字符串语法错误
components/BlogPost.js中拼接详情页路径时,把模板字符串的插值符号$错写成了&,会导致生成的链接地址错误,后续点击跳转直接404。
- 错误代码片段:
<Link href={`/posts/&{slug}`}>
- 修复后代码:
<Link href={`/posts/${slug}`}>
3. 未定义的style变量打断渲染
BlogPost组件中给作者头像容器写了内联样式style={style.author},但组件内从未定义过style这个对象,代码运行到这里会直接抛出JS错误,打断整个页面的渲染流程,也是白屏的诱因之一。
- 错误代码片段:
<div style={style.author}> <img src={author.picture.url} alt="" /> </div>
- 修复方案:不需要内联样式的话直接删除无效属性即可:
<div> <img src={author.picture.url} alt={author.name} /> </div>
4. 可选兜底优化(避免无数据时报错)
如果GraphCMS后台暂时没有发布文章,posts为空时直接调用map方法会抛出类型错误,可以加一层兜底判断:
<main className={styles.main}> {posts?.length ? posts.map((post) => ( <BlogPost key={post.id} title={post.title} author={post.author} slug={post.slug} coverImage={post.coverImage} date={post.date} /> )) : <p>暂无博客内容</p>} </main>
以上问题全部修复后重启本地开发服务,页面即可正常渲染博客内容。
内容的提问来源于stack exchange,提问作者Anshu Singh
相关产品推荐
相关产品推荐

