导出上下文无法与contextType一起使用

时间:2019-08-28 09:10:36

标签: javascript reactjs

我有一个文件App.js,默认情况下从该文件中导出React组件。除此之外,同一文件还可以导出React Context。

在子组件中使用上下文(使用static contextType = Context)时,我只会收到以下警告:

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也未定义。

但是,在render方法中使用使用者可以很好地工作:

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

为更好地理解此问题,请举一个示例:https://codesandbox.io/s/empty-wood-qzrk1?fontsize=14(请参阅控制台以获取警告)。

我在做什么错了?

2 个答案:

答案 0 :(得分:1)

问题在于,您在App.js和子组件version.js

之间具有周期性依赖关系

要解决该问题,您需要做的就是将上下文创建移到一个单独的文件中

Working demo

答案 1 :(得分:0)

选中此link

对于上下文,我创建了一个文件“ MilestoneContext.js”。从此处导出上下文,并将此上下文导入到两个地方App.jsVersions.js

希望它会对您有所帮助。