【问题标题】:How to migrate to new React lifecycle API?如何迁移到新的 React 生命周期 API?
【发布时间】:2018-08-02 13:46:10
【问题描述】:

如您所知,componentWillReceiveProps 等一些生命周期方法现已弃用。

好吧,我的代码使用了这种生命周期方法,现在我不知道如何迁移到 React 的新 API。

这是我的使用方法:

componentWillReceiveProps(nextProps) {
    if (nextProps.newPost) {
        this.props.posts.unshift(nextProps.newPost);
    }
}

在 react 博客中我可以读到...

与 componentDidUpdate 一起,这个新的生命周期应该涵盖所有 旧组件WillReceiveProps 的用例。

...但是如何实现呢?

【问题讨论】:

  • 嗯,基本上 React 团队指向(如你所提到的)componentDidMount 或者可能使用这里讨论的技术之一:reactjs.org/docs/…componentDidUpdate 可以访问组件的状态一个道具直接,例如:this.propsthis.state。最后,你的这部分代码引起了我的注意:this.props.posts.unshift(nextProps.newPost); 你是在直接在组件的props 上改变posts 数组吗?对我来说,这似乎是一个no-no

标签: reactjs react-redux


【解决方案1】:

componentDidUpdate() 在更新发生后立即被调用。初始渲染不调用此方法。

当组件更新时,以此为契机对 DOM 进行操作。只要您将当前的 props 与以前的 props 进行比较,这也是进行网络请求的好地方(例如,如果 props 没有更改,则可能不需要网络请求)。

componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}

请注意,它必须像上面的示例一样包含在条件中,否则会导致无限循环。

【讨论】:

  • 这会导致不必要的额外渲染。还有其他解决方案吗? getDerivedStateFromProps 可以与 state 中的缓存 props 结合使用,但这很尴尬。
【解决方案2】:

您可以使用 getDerivedStateFromProps 或 componentDidMount,运行生命周期有顺序:

  1. getDerivedStateFromProps
  2. 应该组件更新
  3. 渲染
  4. getSnapshotBeforeUpdate
  5. componentDidUpdate

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多