You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js+GraphCMS博客:Categories.name无法渲染且无报错问题排查

问题:Next.js + GraphCMS 无法渲染分类名称,无报错

我正在用Next.js和GraphCMS搭建博客,能通过GQL查询获取部分内容,但页面上渲染不出categories.name,而且没有任何报错。之前在Sanity.io的电商项目里也遇到过类似问题,想排查原因。

相关代码如下:

组件代码

import React, { useState, useEffect } from 'react'
import Link from 'next/link'
import { getCategories } from '../services'

const Categories = () => {
const [categories, setCategories] = useState([]);

useEffect(() => {
    getCategories()
        .then((newCategories) => setCategories(newCategories))
}, []);

return (
    <div className='bg-white shadow-lg rounded-lg p-8 mb-12'>
        <h3 className='text-xl mb-8 font-semibold border-b pb-4'>
            Categories
        </h3>
        {categories.map((category) => {
            <Link key={category.slug} href={`/category/${category.slug}`}>
                <span className='cursor-pointer block pb-3 mb-3'>
                    {category.name}
                </span>
            </Link>
        })}
    </div>
)
}

GraphQL查询代码

export const getCategories = async () => {
    const query = gql`
        query GetCategories {
            categories {
                name
                slug
            }
        }
    `
    const result = await request(graphqlAPI, query);
    return result.categories;
}

排查与解决方法

1. 修复map回调的返回值问题

这是最直接的原因:你的map回调函数用了大括号{}但没有返回JSX元素,导致map执行后返回的是一个全为undefined的数组,页面自然不会渲染任何内容。

两种修复方式:

  • 把大括号换成小括号(自动返回):
{categories.map((category) => (
    <Link key={category.slug} href={`/category/${category.slug}`}>
        <span className='cursor-pointer block pb-3 mb-3'>
            {category.name}
        </span>
    </Link>
))}
  • 在大括号里手动添加return:
{categories.map((category) => {
    return (
        <Link key={category.slug} href={`/category/${category.slug}`}>
            <span className='cursor-pointer block pb-3 mb-3'>
                {category.name}
            </span>
        </Link>
    )
})}

2. 验证数据是否正确获取

在useEffect里添加日志,确认拿到的数据结构是否符合预期:

useEffect(() => {
    getCategories()
        .then((newCategories) => {
            console.log('获取到的分类数据:', newCategories);
            setCategories(newCategories);
        })
}, []);

检查控制台输出的数组,确保每个对象都有name和slug字段,避免字段名拼写错误(比如GraphCMS里字段是Name而不是name)。

3. 确认GraphQL查询有效性

在GraphCMS的Playground里执行你的查询语句,确认返回的categories数组包含正确的name和slug值,排除查询本身的问题。

4. 关于Sanity项目的类似问题

大概率也是因为相同的原因:循环渲染时未正确返回JSX元素,或者数据结构不匹配。可以用同样的排查思路去回顾之前的代码。


内容的提问来源于stack exchange,提问作者wilcardcharly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 10:50:24