【发布时间】:2020-10-25 02:38:22
【问题描述】:
总结
.
我的尝试:我有一个布局页面,其中包含一个侧边栏、页脚……以及一个内容页面(例如:/pages/home)
我正在寻找一种在常规 /pages/home.js 内使用 React 上下文的方法
相关信息
我已经建立了一个上下文:
import React, { useState, createContext } from "react"
const ShareContext = createContext()
const ShareContextProvider = props => {
const [collapsedShare, setCollapsedShare] = useState(false)
const toggleShare = () => setCollapsedShare(!collapsedShare)
return (
<ShareContext.Provider value={{ collapsedShare, toggleShare: toggleShare }}>
{props.children}
</ShareContext.Provider>
)
}
export { ShareContextProvider, ShareContext }
并将它包裹在我的layout.js 周围:
import { ShareContextProvider } from "../context/ShareContext"
const Layout = props => {
return <ShareContextProvider>{props.children}</ShareContextProvider>
}
我可以在我的侧边栏中“使用”它,这在我的一种布局中被调用(我有一个以上的女巫),我喜欢这样:
sidebar.js
import React, { useContext } from "react"
import { ShareContext } from "../../context/ShareContext"
const Sidebar = ({ siteTitle }) => {
const { collapsedShare, toggleShare } = useContext(ShareContext)
return (
<>
<div
onClick={toggleShare}
className={classNames("show-share showshare", {
clshbt: collapsedShare,
})}
>
Some content here
</div>
</>
)
}
现在我的问题:
如何使用页面中的上下文(例如/pages/home.js?
import React, { useContext } from "react"
import { ShareContext } from "../context/ShareContext"
const { collapsedShare } = useContext(ShareContext) <<<<------ When I add this line, everything breaks
当我尝试使用与sidebar.js 相同的方法时,它不会起作用并引发错误:
react.development.js:1465 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https :// fb .me/react-invalid-hook-call for tips about how to debug and fix this problem.
我不得不提一下,我对 Gatsby 和 React 还很陌生
我创建了一个模板来指出问题: https://github.com/exocode/gatsby-context-problem
在此先感谢
【问题讨论】:
-
你可以在这里看到我的类似解决方案:stackoverflow.com/questions/62726519/…
标签: reactjs react-hooks react-context