Skip to content

Instantly share code, notes, and snippets.

@ika18
Last active July 2, 2020 05:54
Show Gist options
  • Save ika18/8f59dfbf6d3dc3048c0fd8522b8a19a6 to your computer and use it in GitHub Desktop.
Save ika18/8f59dfbf6d3dc3048c0fd8522b8a19a6 to your computer and use it in GitHub Desktop.
React Memo的最小实现
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