Skip to content

context

与之前的版本相比,在 React19 中,context 有一些细微的变化。主要体现在如下三个方面。

1、删除旧版 Context

旧版本的 Context 在 2018 年 10 月(v16.6.0)被废弃。但是为了保证平滑的升级,旧版代码一直沿用到了现在。在 React 19 中,这些代码会正式被删除。旧版本的 Context 仅在使用 contextTypes 和 getChildContext API 的类组件中可用。因此它的删除对现在的项目应该只会造成很小的影响。

如果你在项目中仍然使用了旧版 Context,你可以参考下面新旧版本的对比写法进行调整升级。

tsx
// 之前
import PropTypes from 'prop-types';

class Parent extends React.Component {
  static childContextTypes = {
    foo: PropTypes.string.isRequired,
  };

  getChildContext() {
    return { foo: 'bar' };
  }

  render() {
    return <Child />;
  }
}

class Child extends React.Component {
  static contextTypes = {
    foo: PropTypes.string.isRequired,
  };

  render() {
    return (
      <div>
        {this.context.foo}
        {' '}
      </div>
    );
  }
}
tsx
// 之后
const FooContext = React.createContext();

class Parent extends React.Component {
  render() {
    return (
      <FooContext value="bar">
        <Child />
      </FooContext>
    );
  }
}

class Child extends React.Component {
  static contextType = FooContext;

  render() {
    return <div>{this.context}</div>;
  }
}

2、简化 Provider 的使用

在以前的使用中,我们需要使用 Context.Provider 来包裹子组件。

tsx
<Context.Provider value={value}>
  {props.children}
</Context.Provider>;

在 React19 中,我们可以直接使用 Context 来代替 Provider,从而让代表变得更加简洁。

tsx
<Context value={value}>
  {props.children}
</Context>;

3、可以使用 use 获取 context

以前的版本中,在组件内部我们使用 useContext 来获取 context 中的状态。

tsx
// after
import { use } from 'react';

function MyComponent() {
  const theme = use(ThemeContext);
  // ...
}

Contributors

作者:Long Mo
字数统计:351 字
阅读时长:1 分钟
Long Mo
文章作者:Long Mo
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Longmo Docs