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

Next.js动态路由报错:getStaticPaths未提供字符串类型slug参数

问题分析与修复方案

核心错误原因

你遇到的 Error: A required parameter (slug) was not provided as a string in getStaticPaths for /roupas/[slug],本质是在getStaticPaths生成路径时,没有正确从GraphQL返回数据中提取slug值。

从你的GraphQL查询结构可以看到,slug嵌套在attributes对象里,但你在map回调中直接解构{slug},导致提取到的slug为undefined,不符合Next.js对动态路由参数的字符串类型要求。

具体修复步骤

1. 修正getStaticPaths中的slug提取逻辑

修改map回调,从attributes中正确解构slug:

export async function getStaticPaths(){
    const apolloClient = initializeApollo()
    const {data} = await apolloClient.query({query:GET_CARDS})
    const memorySlugs = data.cards.data;
    // 从attributes中提取slug
    const paths = memorySlugs.map(({attributes: {slug}})=>({
       params:{slug}
    }))
    return {paths,fallback:true}
}

2. 修复getStaticProps中的拼写错误

代码里的!data.cards.lenght是拼写错误,改为length:

export async function getStaticProps({params}){
    const apolloClient = initializeApollo()
    const {data} = await apolloClient.query({query:GET_CARD_BY_SLUG, variables:{slug:`${params?.slug}`}})
    // 修正拼写:lenght → length
    if(!data.cards.length){
        return {notFound:true}
    }
    const card = data.cards[0]

    return{
        props:{
            revalidate:60,
            titulo:card.titulo
        }
    }
}

3. 优化Apollo Client初始化(推荐)

不要在全局初始化apolloClient,而是在每个getStatic函数内部初始化,避免跨请求的状态污染:

// 移除全局的 const apolloClient = initializeApollo()

// 在getStaticPaths内部初始化
export async function getStaticPaths(){
    const apolloClient = initializeApollo()
    const {data} = await apolloClient.query({query:GET_CARDS})
    // ...后续逻辑不变
}

// 在getStaticProps内部初始化
export async function getStaticProps({params}){
    const apolloClient = initializeApollo()
    const {data} = await apolloClient.query({query:GET_CARD_BY_SLUG, variables:{slug:`${params?.slug}`}})
    // ...后续逻辑不变
}

额外检查点

  • 确认GET_CARD_BY_SLUG查询能正确接收slug变量,并返回预期的数据结构,避免data.cards为空。
  • 当fallback:true时,建议在页面组件的router.isFallback状态下返回加载提示(比如<p>加载中...</p>),而非null,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:40:27