在16.3.0中引入的React中切换到新的Context API之后,即使官方文档告诉您使用它,这个.context也显示为已弃用:
class MyClass extends React.Component {
componentDidMount() {
let value = this.context;
/* perform a side-effect at mount using the value of MyContext */
}
componentDidUpdate() {
let value = this.context;
/* ... */
}
componentWillUnmount() {
let value = this.context;
/* ... */
}
render() {
let value = this.context;
/* render something based on the value of MyContext */
}
}
MyClass.contextType = MyContext;
在您的案例中使用的上下文API在版本16.3.0和16.6.0之后是受支持的。
API在16.3.0到16.6.0之间略有变化,您需要使用Consumer渲染道具模式,但后来经过改进以支持contextType模式以允许在生命周期方法中使用Context
如果您使用的是上述API,请确保您使用的是16.6.0以上版本的React
如果您使用的是16.3.0到16.6.0之间的版本,请使用上下文
class MyClass extends React.Component {
componentDidMount() {
let value = this.props.context;
/* perform a side-effect at mount using the value of MyContext */
}
componentDidUpdate() {
let value = this.props.context;
/* ... */
}
componentWillUnmount() {
let value = this.props.context;
/* ... */
}
render() {
let value = this.props.context;
/* render something based on the value of MyContext */
}
}
export default (props) => (
<MyContext.Consumer>
{(context) => <MyClass {...props} context={context}/>}
</MyContext.Consumer>
)