Reactjs,this.context 已弃用

标签 reactjs

在 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/

相关文章:

javascript - React 树 - 如何删除当前节点?

javascript - 在参数中传递值时出现错误无法读取未定义的属性 'value'

javascript - React.js 和 HTML5 电子邮件验证

reactjs - 这些都是高阶组件吗?

reactjs - componentDidUpdate 是否在所有子项更新后运行?

javascript - 在 React Native 中获取 API 之前如何保存当前位置的经纬度坐标?

node.js - 如何在React-Redux中上传多个文件

javascript - 在 React.JS 中,如何在渲染字段的组件上设置 readOnly 属性

javascript - 如何测试 shouldComponentUpdate 方法?

reactjs - React 从嵌套元素中的另一个组件更新组件