React 不使用Consumer时createContext,Cannot access 'XXX' before initialization

https://stackoverflow.com/questions/56384761/cannot-access-class-contexttype-within-a-child-component
先说明一下demo的文件

image.png

总共三个文件,ancestors为祖先组件,Father为父组件,Son为子组件

出现问题的时候代码思路如下
Ancestors.jsx提供数据给Son.js,提供数据方式为导出createContext()创建的上下文
Son.js中利用static contextType = MyContext;Son.contextType = MyContext;来使用上下文
详情可见https://reactjs.org/docs/context.html#classcontexttype
代码如下

//ancestors.jsx
import React, {Component} from 'react';
import Father from './Father'

export const MyCtx = React.createContext()
const {Provider, Consumer} = MyCtx

class Ancestors extends Component {

  state = {
    name: 'jack',
    age: 18
  }

  render() {
    return (
        

这是祖先组件

); } } export default Ancestors

Son.js

//Son.js
import React, {Component} from 'react';

class Son extends Component {
  // static contextType=MyCtx
  render() {
    // const {name,age}=this.context
    return (
        
来自祖先组件的值name:{this.context.name},age:{this.context.age}
); } } Son.contextType=MyCtx export default Son;

然而报错


image.png

解决方案:另外找一个文件创建上下文,并导出给ancestors和son使用
增加一个MyContext.js文件创建上下文并导出

import React from "react";

export const MyCtx = React.createContext()

Ancestors中删除创建上下文并导出的部分,使用MyContext.js的上下文

import React, {Component} from 'react';
import Father from './Father'
import {MyCtx} from './MyContext'//这个导入

// export const MyCtx=React.createContext()//这个删掉
const {Provider} = MyCtx

class Ancestors extends Component {

  state = {
    name: 'jack',
    age: 18
  }

  render() {
    return (
        

这是祖先组件

); } } export default Ancestors

Son中代码修改导入上下文的部分

import {MyCtx} from "./MyContext";//改这一行
import React, {Component} from 'react';

class Son extends Component {
  // static contextType=MyCtx
  render() {
    // const {name,age}=this.context
    return (
        
来自祖先组件的值name:{this.context.name},age:{this.context.age}
); } } Son.contextType=MyCtx export default Son;

你可能感兴趣的:(React 不使用Consumer时createContext,Cannot access 'XXX' before initialization)