【问题标题】:componentWillMount is deprecated and will be removed in the next major version 0.54.0 in React NativecomponentWillMount 已弃用,将在 React Native 的下一个主要版本 0.54.0 中删除
【发布时间】:2018-08-18 18:20:36
【问题描述】:

我使用 react native 最新版本的 0.54.0 并且每当在 iOS 上运行应用程序时,都会发现有关弃用生命周期方法的警告。并请更新组件。

警告:

componentWillMount 已弃用,将在下一个主要版本中删除。请改用 componentDidMount。作为临时解决方法,您可以重命名为 UNSAFE_componentWillMount。 请更新以下组件:Container、Text、TouchableOpacity、Transitioner、View

我也有根据waring添加前缀UNSAFE_的方法更改每个方法。

UNSAFE_componentDidMount() {
}
UNSAFE_componentWillMount() {
}
UNSAFE_componentWillUpdate(nextProps, nextState) {
}
UNSAFE_componentWillReceiveProps(nextProps) {
}

虽然警告还在继续。请帮帮我。

目前我已经在我的应用程序中隐藏了 YellowBox 警告。

import { YellowBox } from 'react-native';

render() {

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

【问题讨论】:

  • 我也在我的 SSR 网络应用程序中使用componentWillMount...似乎有关于添加componentWillServerRender 的讨论(可能会被命名为其他名称)github.com/reactjs/rfcs/pull/8/files/… 所以另一种选择可能是否要推迟升级,直到尘埃落定,然后换成新的挂钩? (如果他们被添加......如果没有。我猜又恐慌了)

标签: react-native react-native-android react-native-ios


【解决方案1】:

您应该将所有代码从 componentWillMount 移动到构造函数或 componentDidMount。

componentWillMount() 在挂载之前被调用。它在 render() 之前调用,因此在该方法中同步调用 setState() 不会触发额外的渲染。通常,我们建议使用 constructor() 代替。 避免在此方法中引入任何副作用或订阅。对于这些用例,请改用 componentDidMount()。 这是在服务器渲染上调用的唯一生命周期钩子。

componentDidMount() 在组件安装后立即调用。需要 DOM 节点的初始化应该放在这里。如果您需要从远程端点加载数据,这是一个实例化网络请求的好地方。 此方法是设置任何订阅的好地方。如果你这样做了,不要忘记在 componentWillUnmount() 中取消订阅。 在此方法中调用 setState() 将触发额外的渲染,但它会在浏览器更新屏幕之前发生。这保证了即使在这种情况下 render() 将被调用两次,用户也不会看到中间状态。请谨慎使用此模式,因为它通常会导致性能问题。但是,对于模态框和工具提示等情况,当您需要在渲染取决于其大小或位置的内容之前测量 DOM 节点时,它可能是必要的。

From the official docs

【讨论】:

  • 我没有任何带有componentWillMount 的显着位置,但我在app.js 中确实有一行代码在带有state={ tabindex:0 } 的构造函数之后我如何将其“移动”到构造函数?
  • constructor(props) {super(props); this.state = { tabindex:0 }}
【解决方案2】:

componentDidMount 没有被弃用,并且绝对可以安全使用,因此无需在该方法中添加UNSAFE_。 componentWillSomething 方法似乎即将淘汰。而不是componentWillMount,对不会产生副作用的东西使用构造函数,对会产生副作用的东西使用componentDidMount

【讨论】:

    【解决方案3】:

    您应该避免使用componentWillSomething,以便使用constructorcomponentDidMount

    然而,你必须非常小心你将使用哪一个。一个典型的场景是当你想在打开屏幕后立即显示加载(使用状态)

    this.setState({ isLoading: true });
    ...
    this.setState({ isLoading: false});
    

    在这种情况下,您必须使用componentDidMount 来设置状态。这就是 React 所说的 constructors

    通常,在 React 中构造函数仅用于两个目的:

    1. 通过将对象分配给 this.state 来初始化本地状态。

    2. 将事件处理程序方法绑定到实例。

    你不应该在constructor()中调用setState()。相反,如果您的组件需要使用 localstate,则直接在构造函数中将初始状态分配给 this.state。

    编码不错!

    【讨论】:

      猜你喜欢
      • 2018-08-21
      • 2021-05-09
      • 2021-07-16
      • 1970-01-01
      • 2021-05-17
      • 2021-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多