如何迁移到新的 React 生命周期 API? [英] How to migrate to new React lifecycle API?

查看:63
本文介绍了如何迁移到新的 React 生命周期 API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如您所知,某些生命周期方法(例如 componentWillReceiveProps)现已弃用.

As you know some lifecycle methods like componentWillReceiveProps are now deprecated.

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

Well, my code used this lifecycle method and now I have no idea how to migrate to the new API of React.

这是我的使用方法:

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

在反应博客中,我可以读到...

In the react blog I could read that...

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

Together with componentDidUpdate, this new lifecycle should cover all use cases for the legacy componentWillReceiveProps.

...但是如何实现呢?

... but how to implement this?

推荐答案

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

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

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

Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).

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

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

Note that it must be wrapped in a condition like in the example above, or you’ll cause an infinite loop.

这篇关于如何迁移到新的 React 生命周期 API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆