在 React 组件生命周期方法中,`this.context` 是一个空对象

big*_*ose 4 reactjs

为什么this.context在这个 React 组件生命周期方法中是一个空对象?

上下文在该上下文中具有正确的值Consumer。只有this.contextAPI 失败了。

const LoremContext = React.createContext({
    lorem: "ipsum",
})


class MenuItem extends React.Component {

    componentDidMount() {
        console.log(
            "In MenuItem.componentDidMount, this.context is:",
            this.context)
    }

    render() {
        console.log(
            "In MenuItem.render, this.context is:",
            this.context)
        return ( <LoremContext.Consumer>{
            (lorem) => {
                console.log("In LoremContext.Consumer, lorem is:", lorem)
                return (
                    <li>
                        { `Eat ${this.props.dish} at ${lorem}` }
                    </li>
                )
            }
        }</LoremContext.Consumer> )
    }
}

MenuItem.contextType = LoremContext

class Menu extends React.Component {
    render() {
        …
    }
}

class Application extends React.Component {
    render() {
        return (
            <LoremContext.Provider value={ this.props.world.lorem }>
                <section className="app">
                    <Menu menuItems={ [ … ] } />
                <p>Fusce varius id arcu egestas sodales</p>
            </section>
        </LoremContext.Provider>
    )
}

ReactDOM.render(
    <Application world={ { lorem: "consecteur" } } />,
    document.getElementById('app-container'),
)
Run Code Online (Sandbox Code Playgroud)

这是使用 React 16.4,因此它使用了文档化的上下文 API(在 React 16.3 中引入)。

根据该文档化的 API,上面的代码应该通过React.createContext两种方式访问上下文(在 的返回值中定义):

  • LoremContext.Consumer组件接收LoremContext.Provider.

    然后,使用者将该上下文值作为该组件内函数的参数提供。在这种情况下,lorem是接收上下文值的参数。

  • this.context属性在“生命周期方法”中接收(由于声明的MenuItem.contextType类属性)上下文值。

其中只有一个对我有用。

  • LoremContext.ConsumerAPI是获取和正确地传递上下文值。该console.log输出是:
  In LoremContext.Consumer, lorem is: consecteur
Run Code Online (Sandbox Code Playgroud)
  • this.context没有得到正确的值,而是得到一个空对象。该console.log输出是:
  In MenuItem.render, context is: Object {  }
  In MenuItem.componentDidMount, context is: Object {  }
Run Code Online (Sandbox Code Playgroud)

所以消费者正在接收正确的值,但this.context不是。为什么会有差异?我怎样才能获得在 接收到的正确值this.context

Agn*_*ney 5

this.context是在 React 16.6 中引入的,你可以在这里看到

在此版本之前,在您使用的16.4 上,可以实现在 React Lifecycles 中访问上下文:

class Button extends React.Component {
  componentDidMount() {
    // ThemeContext value is this.props.theme
  }

  componentDidUpdate(prevProps, prevState) {
    // Previous ThemeContext value is prevProps.theme
    // New ThemeContext value is this.props.theme
  }

  render() {
    const {theme, children} = this.props;
    return (
      <button className={theme || 'light'}>
        {children}
      </button>
    );
  }
}

export default props => (
  <ThemeContext.Consumer>
    {theme => <Button {...props} theme={theme} />}
  </ThemeContext.Consumer>
);
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅文档