导出上下文不适用于 contextType

And*_*mdt 4 javascript reactjs

我有一个文件App.js,从中默认导出一个 React 组件。除此之外,同一个文件导出了一个 React Context。

在子组件中使用 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.
Run Code Online (Sandbox Code Playgroud)

this.context 也是未定义的。

但是,在 render 方法中使用消费者效果很好:

<Context.Consumer>{({ name }) => <p>{name}</p>}</Context.Consumer>
Run Code Online (Sandbox Code Playgroud)

为了更好地理解这个问题,这里有一个例子:https : //codesandbox.io/s/empty-wood-qzrk1?fontsize=14(有关警告,请参阅控制台)。

我究竟做错了什么?

Shu*_*tri 10

问题是你在 App.js 和子组件之间有一个循环依赖 version.js

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

工作演示