首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Reactjs,this.context已弃用

Reactjs,this.context已弃用
EN

Stack Overflow用户
提问于 2018-11-20 14:18:35
回答 2查看 4.2K关注 0票数 16

在16.3.0中引入的React中切换到新的上下文API后,this.context被显示为不推荐使用,尽管官方文档告诉你应该这样使用它:

代码语言:javascript
复制
 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;
EN

回答 2

Stack Overflow用户

发布于 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之间的版本,请使用上下文,如

代码语言:javascript
复制
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>
)
票数 4
EN

Stack Overflow用户

发布于 2019-10-08 01:10:19

或者使用带有钩子useContext的函数包装器

代码语言:javascript
复制
export const withMyContext = WrappedComponent => props => {
  const myContext = useContext(MyContext)
  return <WrappedComponent myContext={myContext} {...props} />
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53387299

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档