Created
March 7, 2018 11:30
-
-
Save sivcan/e4dbeb1efcc4ffbc648d492e19506972 to your computer and use it in GitHub Desktop.
React utility for nextProps diff (Shallow check)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Use it with the componentWillReceiveProps lifecycle method | |
// | |
// componentWillReceiveProps(nextProps) { | |
// shallowEqual(this.props, nextProps); | |
// } | |
// | |
function shallowEqual(objA, objB) { | |
if (is(objA, objB)) return true | |
if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) { | |
return false | |
} | |
const keysA = Object.keys(objA) | |
const keysB = Object.keys(objB) | |
if (keysA.length !== keysB.length) return false | |
for (let i = 0; i < keysA.length; i++) { | |
if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { | |
console.log(keysA[i]); | |
return false | |
} | |
} | |
return true | |
} | |
function is(x, y) { | |
if (x === y) { | |
return x !== 0 || 1 / x === 1 / y | |
} else { | |
return x !== x && y !== y | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment