【发布时间】:2021-03-06 15:54:02
【问题描述】:
我是 React 的新手,我正在尽我最大的努力组合一个应用程序,所以我创建了两个主要部分,我想将它们组合起来,但我不是完全确定如何去做。
这是我得到的错误:
TypeError: Cannot read property 'openSidebar' of undefined
它指向这个组件:
// Sidebar button and opening of sidebar
// main function created to open sidebar button
import React from 'react';
import { FaBars } from 'react-icons/fa';
import { useGlobalContext } from './context';
const Home = () => { /*const data can setup data form each button under sidebar */ //<----- ERROR HERE
const { openSidebar } = useGlobalContext();
return (
<main>
<button onClick={openSidebar} className='sidebar-toggle'>
<FaBars />
</button>
</main>
);
};
export default Home;
我已经通过多种方式搜索了错误,但它们似乎都与它们发生的应用程序相关。
感谢您提供的任何帮助。 如果需要更多信息,请告诉我!
编辑:
下面是处理constopendSidebar的组件
// context class need to be added without change,
// setting of close open sidebar
import React, { useState, useContext } from 'react';
const AppContext = React.createContext(undefined, undefined);
const AppProvider = ({ children }) => {
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
const openSidebar = () => {
setIsSidebarOpen(true);
};
const closeSidebar = () => {
setIsSidebarOpen(false);
};
return (
<AppContext.Provider
value={{
isSidebarOpen,
openSidebar,
closeSidebar,
}}
>
{children}
</AppContext.Provider>
);
};
export const useGlobalContext = () => {
return useContext(AppContext);
};
export { AppContext, AppProvider };
【问题讨论】:
-
看来
useGlobalContext正在返回undefined。没有看到它是如何实现的,很难说更多。 -
我已经添加了处理
useGlobalContext和openSidebar的组件 -
<Home />需要包裹在更高的<AppProvider />中。这可能在您的根级别<App />组件中。
标签: javascript html css reactjs node-modules