【问题标题】:Rename componentWillReceiveProps to componentDidUpdate将 componentWillReceiveProps 重命名为 componentDidUpdate
【发布时间】:2023-03-02 23:00:02
【问题描述】:

我正在按照本教程构建一个可扩展的列表视图:

https://medium.com/@iakash1195/expandable-listview-in-react-native-53ebdd78abea

它有效,但我收到一条警告说:

警告:componentWillReceiveProps 已被重命名,而不是 推荐使用。看 fb.me/react-unsafe-component-lifecycles 了解详情。

  • 将数据获取代码或副作用移至 componentDidUpdate。
  • 如果您在 props 更改时更新状态,请重构您的代码以使用记忆技术或将其移动到静态 getDerivedStateFromProps。了解更多信息:
  • 将 componentWillReceiveProps 重命名为 UNSAFE_componentWillReceiveProps 以在非严格模式下抑制此警告。在 React 17.x 中,只有 UNSAFE_ 名称将起作用。将所有已弃用的生命周期重命名为其 新名字,你可以在里面运行npx react-codemod rename-unsafe-lifecycles 您的项目源文件夹。

我尝试将 componentWillReceiveProps 重命名为 componentDidUpdate,但可展开的列表视图停止工作

我可以只运行命令来重命名已弃用的函数,但这个解决方案远不是最好的。

npx react-codemod rename-unsafe-lifecycles --force

【问题讨论】:

    标签: react-native


    【解决方案1】:

    正如警告所暗示的,componentWillReceiveProps 已被弃用,您应该改用static getDerivedStateFromProps

    static getDerivedStateFromProps(nextProps, prevState) {
      if  (nextProps.item.isExpanded && prevState.layoutHeight) 
        return {
          layoutHeight: null
        };
      return {
        layoutHeight: 0
      };
    }
    

    您可以在getDerivedStateFromProps 阅读有关此生命周期方法的更多信息

    【讨论】:

      【解决方案2】:

      您不应再使用 componentWillReceiveProps。获取道具更改的新的更有效的解决方案是使用函数 getDerivedStateFromProps

      阅读:

      https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-29
        • 2017-10-24
        • 1970-01-01
        • 2020-04-13
        • 2021-01-14
        • 1970-01-01
        • 2018-08-05
        相关资源
        最近更新 更多