簡體   English   中英

如何在React中檢查prevProps和nextProps是否相同?

[英]How to check if prevProps and nextProps are the same in React?

我有這樣的生命周期鈎子

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

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

和道具有這樣的結構

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

我需要檢查隱藏的屬性是否與prev中的相同,以及每個對象中的下一個道具,因此我將知道是否需要在條件或不運行時運行函數。 我怎樣才能做到這一點?

不要使用componentWillReceiveProps - 這個鈎子很快就會被棄用。 componentDidUpdate是您需要的正確鈎子。

問題是您正在進行的比較是淺層比較 - 即它不會比較相應數組中的嵌套值。

基本的想法是你應該遍歷兩個數組並比較各個嵌套值 - 這里有更多關於它的信息: 如何在JavaScript中比較數組?

您還可以使用類似lodash的isEqual方法在兩個數組之間進行深度比較: https ://lodash.com/docs/4.17.10#isEqual

使用componentWillReceiveProps。

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

如果你有對象數組,那么你需要通過比較舊的道具來映射數組中的每個對象。

只有在activeItems元素發生更改的情況下,父組件才能處理此問題以提供不可變的activeItems

否則,如果activeItems數組非常相等,則需要對它們進行測試,例如recompose

import { shallowEqual } from 'recompose'; 

...

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

你現在可以使用componentWillReceiveProps。 因為它很快就會被棄用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM