【问题标题】:How to check if prevProps and nextProps are the same in React?如何检查 React 中的 prevProps 和 nextProps 是否相同?
【发布时间】:2018-10-16 11:26:34
【问题描述】:

我有这样的生命周期钩子

componentDidUpdate(prevProps) {
    // Typical usage (don't forget to compare props):       

    if (prevProps.activeItems !== this.props.activeItems) {
      this.props.doAction();
    }
  }

props有这样的结构

[
  {id:1, hidden: true},
  {id:2, hidden: false}
  {id:3, hidden: true}
]

我需要检查每个对象的 prev 和 next 属性中的 hidden 属性是否相同,所以我会知道是否需要在 if 条件下运行函数。我该怎么做?

【问题讨论】:

  • 你真的不能,这是不可变数据结构的坏处。您必须手动进行检查,我使用array.every,为此

标签: javascript reactjs


【解决方案1】:

不要使用 componentWillReceiveProps——这个钩子很快就会被弃用。 componentDidUpdate 是您需要的正确钩子。

问题在于您正在进行的比较是浅比较——即它不比较各个数组中的嵌套值。

基本思想是您应该遍历两个数组并比较各个嵌套值——这里有更多信息:How to compare arrays in JavaScript?

您还可以使用类似 lodash 的 isEqual 方法在两个数组之间执行深度比较:https://lodash.com/docs/4.17.10#isEqual

【讨论】:

  • 我不使用omponentWillReceiveProps,我知道。我试过 isEqual ,它对我有用。谢谢
【解决方案2】:

利用componentWillReceiveProps。

  componentWillReceiveProps (nextProps) { 
      if(nextProps.something !== this.props.soemthing) {
           //write your statements
      }
  } 

如果你有对象数组,那么你需要通过比较旧道具来映射数组中的每个对象。

【讨论】:

  • reactjs.org/docs/… 并重新检查我的结构,我有对象数组,我需要检查每个对象的属性
  • 所以你不知道,哪个属性被改变了?
  • 隐藏将被更改
  • 您需要通过比较旧的道具来映射数组中的每个对象。
  • 这个我知道,有人问我解决办法
【解决方案3】:

只有在 activeItems 元素发生变化的情况下,父组件才能提供不可变的 activeItems

否则activeItems 数组需要测试它们是否浅相等,例如with recompose:

import { shallowEqual } from 'recompose'; 

...

  componentDidUpdate(prevProps) {
    if (shallowEqual(prevProps.activeItems, this.props.activeItems)) {
      this.props.doAction();
    }
  }

【讨论】:

    【解决方案4】:

    您现在可以使用 componentWillReceiveProps。因为它很快就会被弃用

       componentWillReceiveProps (nextProps) {
           if(nextProps.something === this.props.soemthing) {
               // do your work
           }
       } 
    

    【讨论】:

    • 这个答案有什么错字?仔细看是不一样的。谢谢
    • 不,你的回答完全错误,我说我有 ARAAY OF OBJECTS,我需要检查两个道具的属性
    • 听着 rick,你有对象数组。好的,您将此数组作为该组件中的道具传递。对。现在首先你必须比较旧道具和新道具是不同的,因为每当道具发生变化时,它都会出现在“componentWillRecieveProps”中。假设您在临时命名键中传递该数组。所以 if(nextProps.temp === this.props.temp) { let filtersArray = nextProps.temp.filter((tempObject) => { return "check your condition here"; }) }
    猜你喜欢
    • 1970-01-01
    • 2014-09-19
    • 2019-10-27
    • 1970-01-01
    • 2018-01-28
    • 2020-02-03
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多