在16.3.0中引入的React中切换到新的上下文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;发布于 2018-11-20 14:28:48
在16.3.0和16.6.0版本之前支持使用上下文API,就像您在案例中使用的一样。
在16.3.0到16.6.0之间,API稍有变化,您需要使用Consumer render prop模式,但后来经过改进以支持contextType模式,从而允许在生命周期方法中使用上下文
如果您正在使用如上所述的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>
)发布于 2019-10-08 01:10:19
或者使用带有钩子useContext的函数包装器
export const withMyContext = WrappedComponent => props => {
const myContext = useContext(MyContext)
return <WrappedComponent myContext={myContext} {...props} />
}https://stackoverflow.com/questions/53387299
复制相似问题