【问题标题】:React - how to show the difference between the current and next props?React - 如何显示当前和下一个道具之间的区别?
【发布时间】:2016-11-11 09:30:55
【问题描述】:

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

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

这是怎么做到的?

【问题讨论】:

标签: reactjs


【解决方案1】:

这个 npm 包似乎运行良好:

https://github.com/Tixit/odiff

【讨论】:

    【解决方案2】:

    你可以用下面的函数做一个浅层的比较(我用的是 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
             }
        }
    }
    

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

    【讨论】:

    • 感谢您的回答,尽管我一直在寻找可以分析对象更深层次的东西。
    • @JoeTidee 这个答案正是你所需要的stackoverflow.com/a/1144249/5444014
    • 这些函数只是比较两个对象是否相同,它们不存在差异。
    • 您可以轻松地在函数的开头创建一个空数组,并将您发现的每个差异都推送到其中,而不是返回 false。然后在函数的最后,返回填充后的数组。
    猜你喜欢
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 2016-06-07
    • 2019-03-28
    • 2020-12-31
    相关资源
    最近更新 更多