【问题标题】:Getting an error while trying the context API in React JS. I am using context API with classes in ReactJS在 React JS 中尝试上下文 API 时出错。我在 ReactJS 中使用上下文 API 和类
【发布时间】:2021-11-04 04:21:18
【问题描述】:

我正在我的代码中尝试 React 的上下文 API。我尝试了以下代码并收到错误

ReferenceError:初始化前无法访问“MyContextApi”

Context.api.parent.js

import ContextChildOne from "./Context.api.childone";
import ContextChildTwo from "./Context.api.childtwo";
export const MyContextApi = React.createContext({});

class ContextParent extends React.Component {
  render() {
    return (
      <div>
        <p>context api parent tag</p>
        <MyContextApi.Provider value={{ concept: "Context API" }}>
          <ContextChildOne>
            <ContextChildTwo />
          </ContextChildOne>
        </MyContextApi.Provider>
      </div>
    );
  }
}

export default ContextParent;

我正在以下文件中使用上述上下文 API

Context.api.childtwo.js

import { MyContextApi } from "./Context.api.parent";

class ContextChildTwo extends React.Component {
  //   static contextType = MyContextApi;
  render() {
    // let concept = this.context;
    return (
      <div>
        <p>Child two of context</p>
        <p>
          THIS IS THE EXAMPLE OF CONTEXT API TO AVOID PROPS DRILLDOWN.
          THIS CONCEPT <span>{this.context.concept}</span>
        </p>
      </div>
    );
  }
}
ContextChildTwo.contextType = MyContextApi;
export default ContextChildTwo;

我尝试将export const MyContextApi = React.createContext({}); 保留在其他文件中并导入它,但它没有用,我得到了同样的错误。

请帮我解决这个错误ReferenceError: Cannot access 'MyContextApi' before initialization

【问题讨论】:

    标签: reactjs context-api


    【解决方案1】:

    我将代码export const MyContextApi = React.createContext({}); 移动到另一个文件中,并将其导入到父组件和子组件中。然后,我的代码正常运行,没有错误。

    之前我尝试只在父组件中导入,但没有成功。现在,它正在工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      • 2018-11-14
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多