。
我尝试的方法:我有一个布局页面,其中包含一个侧边栏,页脚,..以及一个内容页面(例如:/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
非常感谢
答案 0 :(得分:0)
像错误消息一样:Hooks can only be called inside of the body of a function component.
这意味着您只能在类似这样的react功能组件中调用它
const MyComponent = () => {
const { collapseShare } = useContext(ShareContext)
}
看看是否可行!
答案 1 :(得分:0)
我遇到了同样的问题,然后意识到,您说挂钩必须在功能组件的主体中。 由于上下文位于布局内,因此只能在布局的子组件中使用上下文。
页面组件是布局的父级,因此请执行以下操作:
// src/pages/mypage.js
export default function MyPage() {
return (<Layout><PageContentComponent /></Layout>);
}
const PageContentComponent = () => {
const shareContext = useContext(shareContext);
return <>...</>
}