如何解决实际需要 componentWillMount 的用例?

How to solve use-cases when componentWillMount is actually needed?

React 将放弃 componentWillMountcomponentWillReceivePropscomponentWillUpdate 生命周期钩子。可以在 Update on Async Rendering 文章中找到更多详细信息。

我对从这些方法迁移有疑问。这是一个例子:

目前,我使用 nprogress 在页面顶部显示进度条。它是这样使用的:

export default class Page extends React.Component {
  componentWillMount() {
    Nprogress.start();
  }

  componentDidMount() {
    Nprogress.done();
  }

  render() {
    return (
      <h1>Hello, world!</h1>
    )
  }
}

在上面的示例中,我在组件安装之前开始显示进度条,并在组件安装完成后完成。

如何迁移到新的 React 生命周期并使我的组件按预期工作?

您应该使用名为 getDerivedStateFromProps 的新静态方法。如果您不需要更新状态,只需 return null.

所以,在你的情况下:

export default class Page extends React.Component {

  static getDerivedStateFromProps(nextProps, prevState) {
     if (!prevState.isMounted) {
        Nprogress.start();

        return {
          isMounted: true
        }
     }

     return null;
  }

  constructor(props) {
     super(props);

     this.state = {
        isMounted: false,
     }
  }

  componentDidMount() {
    Nprogress.done();
  }

  render() {
    return (
      <h1>Hello, world!</h1>
    )
  }
}

希望对您有所帮助。

使用构造函数:

export default class Page extends React.Component {
  constructor(props) {
    super(props);
    Nprogress.start();
  }

  componentDidMount() {
    Nprogress.done();
  }

  render() {
    return (
      <h1>Hello, world!</h1>
    )
  }
}