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

如何在Gatsby动态页面中访问context的页面值?

如何访问Gatsby动态页面context中的值?

我通过createPage函数创建了包含context数据的动态页面,代码如下:

groups.forEach(async node => {
    const id = node.name
   
    actions.createPage({
      path: 'group/'+id,
      component: require.resolve(`./src/pages/groups/index.js`),
      context: { id: id },
    })
  })
....

随后我在生成的页面中编写了GraphQL查询:

import * as React from "react"
import { graphql } from 'gatsby'

const GroupPage = ({data}) => {
 
        return (
            <main >               
                <ul>
                    {
                        data.allAgents.edges.map(node => (
                        <li key={node.node.name}></li>
                        ))
                    }
                </ul>
          
            </main>
        )     
}


export const query = graphql`
query($id: String!)  {
    allAgents (filter: { group: {eq: $id } } ) {
        edges {
          node {
            id
            name
            group
          }
        }
      }
}
`

export default GroupPage

export const Head = () => <title>Group</title>

请问我该如何访问context中的页面值?


有两种常用方式可以访问createPage传入的context值:

1. 通过页面组件props直接获取

页面组件的props中包含pageContext对象,直接解构就能拿到context里的字段:

const GroupPage = ({data, pageContext}) => {
    // 获取context中的id值
    const groupId = pageContext.id;
 
    return (
        <main >               
            <h1>当前分组ID:{groupId}</h1>
            <ul>
                {
                    data.allAgents.edges.map(node => (
                    <li key={node.node.name}>{node.node.name}</li>
                    ))
                }
            </ul>
      
        </main>
    )     
}

2. 通过GraphQL查询变量复用

你已经在查询里定义了$id变量,Gatsby会自动把context中的id值注入到这个变量中,你的查询已经在利用这个值过滤allAgents数据了。如果后续需要在查询中使用其他context字段,只需要在createPage的context里添加对应字段,再在查询里定义对应变量即可。

比如给context新增groupName: node.name,查询可修改为:

query($id: String!, $groupName: String!)  {
    allAgents (filter: { group: {eq: $id } } ) {
        edges {
          node {
            id
            name
            group
          }
        }
      }
}

组件内同样可以通过pageContext.groupName获取该值。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 23:00:55