【问题标题】:React-native lifecycle methods warning: " componentWillReceiveProps is deprecated and will be removed in the next major version"React-native 生命周期方法警告:“ componentWillReceiveProps 已弃用,将在下一个主要版本中删除”
【发布时间】:2018-08-21 20:27:38
【问题描述】:

在 react-native 中使用生命周期方法时,我在控制台和模拟器中遇到了以下警告消息:

警告:componentWillReceiveProps 已弃用,将在下一个主要版本中删除。请改用静态 getDerivedStateFromProps。

警告:componentWillMount 已弃用,将在下一个主要版本中删除。请改用 componentDidMount。作为临时解决方法,您可以重命名为 UNSAFE_componentWillMount。

警告甚至在模拟器中令人讨厌地显示如下:

每当我关闭模拟器中的警告消息时就会出现问题,应用程序崩溃,因此我必须再次重新启动应用程序。 我该怎么办?

此外,尽管有警告消息,但我从未使用过“componentWillReceiveProps”方法。但是,我使用了“componentWillMount”方法。甚至与方法“componentWillReceiveProps”相关的收到警告消息的原因可能是什么?

【问题讨论】:

  • 您在警报中省略了一条可以为您提供更多信息的信息.....url

标签: react-native remote-debugging


【解决方案1】:

我认为它不会影响您的应用程序,只是很烦人。

通过在index.js中添加以下隐藏它:

import { YellowBox } from 'react-native';

YellowBox.ignoreWarnings([
  'Warning: componentWillMount is deprecated',
  'Warning: componentWillReceiveProps is deprecated',
  'Module RCTImageLoader requires',
]);

【讨论】:

    【解决方案2】:

    这些弃用通知不是由于登陆 React Native 0.54 而是错误的,您可以将 React Native 升级到 0.54.1 并看到这些消息消失了。

    阅读更多here

    【讨论】:

    • 如何正确升级到 0.54.1?
    • 没关系,只是在 package.json 中将其更改为 0.54.1,不确定这是否是最好的方法,因为我也看到了 git 方法。
    • 我刚刚在我的 index.js 文件中添加了上面提到的方法,它对我有用!目前!虽然不是永久的解决方案。希望有帮助!!
    【解决方案3】:

    只需替换

    componentWillReceiveProps(nextProps) { ... }

    static getDerivedStateFromProps(nextProps, prevState) { ... }

    并使用prevState 作为您的当前状态。

    请记住,此方法应返回一个对象来更新状态,或者返回 null 以不更新任何内容并且无权访问组件实例。类似redux的东西。 见this

    【讨论】:

      猜你喜欢
      • 2018-08-18
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      • 2019-12-18
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      相关资源
      最近更新 更多