Last active
July 2, 2020 05:54
-
-
Save ika18/8f59dfbf6d3dc3048c0fd8522b8a19a6 to your computer and use it in GitHub Desktop.
React Memo的最小实现
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
const memo = (component, comparision) => { | |
let prevProps = {}; | |
let nextProps = {}; | |
let memoResult = null; | |
let initialized = false; | |
const comparisionFn = comparision ? comparision : (nextProps, prevProps) => { | |
return nextProps === prevProps; | |
} | |
return (props) => { | |
prevProps = nextProps; | |
nextProps = props; | |
if (comparisionFn(nextProps, prevProps) && initialized) { | |
console.log('memorized'); | |
return memoResult; | |
} else { | |
console.log('not memorized'); | |
memoResult = component(props); | |
initialized = true; | |
return memoResult; | |
} | |
}; | |
} | |
const comp = (props) => { | |
return props; | |
} | |
const memoComp = memo(comp); | |
const props1 = {'a': 'hello'} | |
console.log(memoComp(props1)) | |
console.log(memoComp(props1)) | |
console.log(memoComp({'a': 'aaa'})) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment