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

如何在Gatsby中向gatsby-node生成的页面模板传递state?

Gatsby + WordPress:向模板组件传递顶层State的问题与解决

问题描述

我用Gatsby搭配WordPress后端搭建站点,需要把在应用顶层生成的state作为props传给/src/templates/template.js这类模板文件,但始终无法实现:

  • Layout组件能成功把location props传给模板,src/components下的其他组件也能访问该state变量
  • 用Reach Router给Profile组件传state是可行的:
<PrivateRoute path="/app/profile" 
  component={Profile} 
  allUserInfo={allUserInfo} 
  setAllUserInfo={setAllUserInfo}
/>

但用同样方式给src/templates下的CustomPostTypeTemplate组件传state无效:

<CustomPostTypeTemplate
 path="/cpt/:cptSlug"
  component={CustomPostTypeTemplate}
  allUserInfo={allUserInfo} 
  setAllUserInfo={setAllUserInfo}
/>

尝试通配符路径也没用:

<CustomPostTypeTemplate
 path="/cpt/*"
  component={c}
  allUserInfo={allUserInfo} 
  setAllUserInfo={setAllUserInfo}
/>

补充细节:

  • 在gatsby-node中生成自定义页面
  • 曾把模板文件从/src/templates/移到/src/components/,问题依旧

相关代码

app.js

import React from "react"
import { Router, Route } from "@reach/router"
import { useState, useEffect } from 'react';

const [allUserInfo, setAllUserInfo] = useState("");

return (
  <Layout 
    location={location}
    allUserInfo={allUserInfo} 
    setAllUserInfo={setAllUserInfo}
  >
    <Router>
      <Custom
        path="/custom/*"
        component={Custom}
        allUserInfo={allUserInfo} 
        setAllUserInfo={setAllUserInfo}
      />
    </Router>
  </Layout>
)

/src/components/Custom.js

// 导入语句
const Custom = ({ allUserInfo, setAllUserInfo, location, data: { post } }) => {
  console.log(allUserInfo);
  return (
    // 组件内容
  )
}
export default Custom

gatsby-node.js

const createIndividualCustomPages = async ({ customs, gatsbyUtilities }) =>
  Promise.all(
    custom.map(({ custom }) =>
      gatsbyUtilities.actions.createPage({
        path: custom.uri,
        slug: custom.slug,
        // 使用指定组件作为页面模板
        component: path.resolve(`./src/components/Custom.js`),
        // context在模板中作为props和GraphQL变量可用
        context: {
          id: custom.id,
        },
      })
    )
  )

最终解决方案

我用Context Hook包裹了整个应用,以此向应用其余部分传递state和updateState变量/钩子。不过至今仍对Router通配符选项无效的问题感到困惑,但只能先推进开发了。再次感谢@JishanShaikh的热心解答!

内容的提问来源于stack exchange,提问作者Robert J. Peterson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 04:55:34