在 16.3.0 中引入的 React 中切换到新的 Context API 后,this.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;
最佳答案
版本 16.3.0 之前和版本 16.6.0 之后支持使用您在案例中使用的上下文 API。
API 在 16.3.0 到 16.6.0 之间发生了一些变化,您需要使用 Consumer 渲染 Prop 模式,但后来进行了改进以支持 contextType 模式,以允许在生命周期方法中使用 Context
如果您使用上述 API,请确保您使用的 React 版本高于 16.6.0
如果您使用的是 16.3.0 到 16.6.0 之间的版本,请使用 Context,例如
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>
)
关于Reactjs,this.context 已弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53387299/