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



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

上下文在该上下文的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'),
)

这是使用 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
  • this.context没有获得正确的值,而是获取一个空对象。console.log输出为:
In MenuItem.render, context is: Object {  }
In MenuItem.componentDidMount, context is: Object {  }

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

this.context是在 React 16.6 中引入的,您可以在此处看到

在此版本之前,在您使用的 16.4 上,可以访问 React 生命周期中的上下文:

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>
);

有关详细信息,请参阅文档

尝试在单独的文件中创建上下文,然后将其导入。 这对我有用。 当在使用<MyContext.Provider>标记的同一文件中调用createContext时,使用者只能看到一个空对象。 当我createContext移动到单独的文件时,使用者看到了预期的值。 这适用于两种消费方法 -<MyContext.Consumer>MyClass.contextType/this.context.

恐怕我无法解释为什么这有效,但我在这个线程中找到了解决方案。

不幸的是,目标组件中没有这个部分,它是空的。

static contextType = ThemeContext; // assign the correct context 

创建之前喜欢

const ThemeContext = React.createContext('light');

https://reactjs.org/docs/context.html

最新更新