【问题标题】:createContext hook not working for react components inside JSPcreateContext 钩子不适用于 JSP 中的反应组件
【发布时间】:2020-05-07 21:13:48
【问题描述】:

我正在使用

在现有 JSP 页面中呈现我的反应组件
ReactDOM.render(
      React.createElement(MyReactComponents.myReactComponent, {
        props
      }),
  document.querySelector("#id")
);

而react组件如下:

import MyStore from "./MyStore";
const MyReactComponent: React.FC<any> = (props: any) => {
      const store = useContext(MyStore);
      store.myFunction();
      ---code---
}

而MyStore如下:

export class MyStore{
      ---Code---
}
export default createContext(new MyStore());

但我收到此错误:

还有一点需要注意的是,当我尝试在另一个现有的 react 组件之上渲染这个 react 组件时,我没有收到任何错误并且一切正常。

有人可以解释一下可能导致问题的原因吗?

【问题讨论】:

    标签: reactjs jsp react-hooks mobx-react use-context


    【解决方案1】:

    我不确定,但也许你误用了useContext 钩子?

    每当您在组件Child 中使用它时,它的父组件中至少有一个必须调用&lt;Context&gt;.Provider,以便在树的下方对其进行初始化。

    在您的示例中,您使用ReactDOM.render 渲染MyReactComponent:因此,我想MyReactComponent 是您树中的第一个组件。如果是这种情况,当您在其中使用useContext 时,它找不到任何MyStore 上下文。

    因此,您可能只需要使用上下文提供程序包装您的 MyReactComponent。

    export class MyStore { ... }
    export const MyStoreContext = createContext(new MyStore());
    
    ---
    
    ReactDOM.render(
        <MyStoreContext.Provider>
            <MyReactComponent {...props />
        </MyStoreContext.Provider>
    , document.querySelector("#id"));
    

    然后,在MyReactComponent 中,您可以使用const store = useContext(MyStoreContext);。

    【讨论】:

      猜你喜欢
      • 2022-11-12
      • 1970-01-01
      • 2020-03-31
      • 1970-01-01
      • 2021-06-08
      • 2021-05-19
      • 1970-01-01
      • 2020-09-17
      • 2019-07-07
      相关资源
      最近更新 更多