React-native 生命周期方法警告:“componentWillReceiveProps 已弃用,将在下一个主要版本中删除”

React-native lifecycle methods warning: " componentWillReceiveProps is deprecated and will be removed in the next major version"

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

Warning: componentWillReceiveProps is deprecated and will be removed in the next major version. Use static getDerivedStateFromProps instead.

Warning: componentWillMount is deprecated and will be removed in the next major version. Use componentDidMount instead. As a temporary workaround, you can rename to UNSAFE_componentWillMount.

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

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

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

我觉得不影响你的申请,就是烦人而已。

通过将下面的内容添加到 index.js 来隐藏它:

import { YellowBox } from 'react-native';

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

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

阅读更多here

只需更换

componentWillReceiveProps(nextProps) { ... }

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

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

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