【问题标题】:React Components from Separate App not integrating into Main App来自单独应用程序的反应组件未集成到主应用程序中
【发布时间】: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。没有看到它是如何实现的,很难说更多。
  • 我已经添加了处理useGlobalContextopenSidebar的组件
  • &lt;Home /&gt; 需要包裹在更高的&lt;AppProvider /&gt; 中。这可能在您的根级别 &lt;App /&gt; 组件中。

标签: javascript html css reactjs node-modules


【解决方案1】:

正如我在评论中提到的,您似乎缺少&lt;AppProvider /&gt;。这为所有感兴趣的孩子提供了context 值。如果找不到上下文提供程序,则将使用提供给createContext(在您的情况下为未定义)的defaultValue

请查看this 示例。特别是根App.js。你会看到一个类似于

的结构
<AppProvider>
  <Home />
<AppProvider />

这确实是唯一缺少的东西。

【讨论】:

    【解决方案2】:

    在 React 中,Context 用于共享全局属性 - 从而避免了将属性向下传递多个级别的需要。 ContextProvider 仍然需要在组件的父层次结构中,以便深度嵌套的组件可以访问上下文属性。

    在您的程序中,将“Home”组件包含在 AppProvider 中。 [ AppProvider 中的 {children} 变量将指向“Home”组件。]

     <AppProvider>
          <Home/>
      </AppProvider>
    

    现在,您需要在组件内使用上下文属性。这是通过钩子 useContext 完成的。

      const { openSidebar } = useContext(AppContext);
    

    子组件(Home)现在可以访问最近的 AppContext(您可以嵌套多个 AppProviders - 子组件将使用最近的 Context)。

    [你不需要 useGlobalContext 函数。上下文已在您的程序中导出。在“Home”组件中,使用钩子“useContext”并将 AppContext 作为参数传递。]

    完整的程序在这里 -

    https://codesandbox.io/s/react-context-integration-wfup1?file=/src/App.js

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-11
      • 1970-01-01
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多