React - 如何显示当前和下一个道具之间的区别?

时间:2016-11-11 00:45:14

标签: reactjs

我想展示组件当前和下一个道具之间的区别。例如:

componentWillReceiveProps(nextProps) {
    let diff = someFunction(this.props, nextProps);
    console.log(diff);
} 

这是怎么做到的?

2 个答案:

答案 0 :(得分:0)

您可以使用如下函数进行浅层比较(我使用ES6):

function compareObjects (objectA, objectB) {
    if (objectA === objectB) {
        return true // return true if both variables are referencing the same object
    }

    let key

    // check what property does objectA have that objectB has not
    for (key in objectA) {
         if (objectA.hasOwnProperty(key) && !objectB.hasOwnProperty(key)) {
              return false // return false if there's a difference
         }
    }

    // check what property does objectB have that objectA has not
    for (key in objectB) {
         if (objectB.hasOwnProperty(key) && !objectA.hasOwnProperty(key)) {
              return false // return false if there's a difference
         }
    }
}

请注意,这只是浅层检查,并在第一级进行比较。它只比较给定的对象是否包含相同的值(因此它被称为浅)。

答案 1 :(得分:0)

这个npm包看起来效果很好:

https://github.com/Tixit/odiff