admin管理员组

文章数量:1317915

I have a file App.js, from which a React ponent is exported as default. Besides that, the same file exports a React Context.

When using the Context in a child ponent (using static contextType = Context), I just get the following warning:

Warning: Versions defines an invalid contextType. contextType should point to the Context object returned by React.createContext(). However, it is set to undefined. This can be caused by a typo or by mixing up named and default imports. This can also happen due to a circular dependency, so try moving the createContext() call to a separate file.

this.context is also undefined.

However, using the consumer in the render method works just fine:

<Context.Consumer>{({ name }) => <p>{name}</p>}</Context.Consumer>

To better understand the issue, here's an example: (see the console for the warning).

What am I doing wrong?

I have a file App.js, from which a React ponent is exported as default. Besides that, the same file exports a React Context.

When using the Context in a child ponent (using static contextType = Context), I just get the following warning:

Warning: Versions defines an invalid contextType. contextType should point to the Context object returned by React.createContext(). However, it is set to undefined. This can be caused by a typo or by mixing up named and default imports. This can also happen due to a circular dependency, so try moving the createContext() call to a separate file.

this.context is also undefined.

However, using the consumer in the render method works just fine:

<Context.Consumer>{({ name }) => <p>{name}</p>}</Context.Consumer>

To better understand the issue, here's an example: https://codesandbox.io/s/empty-wood-qzrk1?fontsize=14 (see the console for the warning).

What am I doing wrong?

Share Improve this question asked Aug 28, 2019 at 9:10 Andreas RemdtAndreas Remdt 6551 gold badge9 silver badges16 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 11

The problem is that you have a cyclic dependency here between App.js and the child ponent version.js

To solve the problem, all you need to do is to move context creation into a separate file

Working demo

Check this link

For the context I have created a single file 'MilestoneContext.js'. Exported the context from here and imported this context to both places App.js and Versions.js.

Hope it will help you.

本文标签: javascriptExporting Context not working with contextTypeStack Overflow