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 badges2 Answers
Reset to default 11The 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
版权声明:本文标题:javascript - Exporting Context not working with contextType - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742025393a2415444.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论