跳到主要内容

React 记忆化

// 记忆化
export function memo<Props>(
type: React$ElementType,
compare?: (oldProps: Props, newProps: Props) => boolean,
) {
if (__DEV__) {
if (type == null) {
console.error(
'memo: The first argument must be a component. Instead ' +
'received: %s',
type === null ? 'null' : typeof type,
);
}
}
const elementType = {
$$typeof: REACT_MEMO_TYPE,
type,
compare: compare === undefined ? null : compare,
};
if (__DEV__) {
let ownName;
Object.defineProperty(elementType, 'displayName', {
enumerable: false,
configurable: true,
get: function () {
return ownName;
},
set: function (name) {
ownName = name;

// The inner component shouldn't inherit this display name in most cases,
// because the component may be used elsewhere.
// But it's nice for anonymous functions to inherit the name,
// so that our component-stack generation logic will display their frames.
// An anonymous function generally suggests a pattern like:
//
// 在大多数情况下,内部组件不应该继承这个显示名称,因为该组件可能在其他地方使用。
// 但是让匿名函数继承名称是有好处的,这样我们的组件堆栈生成逻辑就能显示它们的帧。
// 匿名函数通常表明一种模式,例如:
//
// React.memo((props) => {...});
//
// This kind of inner function is not used elsewhere so the side effect is okay.
// 这种内部函数不会在其他地方使用,所以这个副作用是可以接受的。
if (!type.name && !type.displayName) {
Object.defineProperty(type, 'name', {
value: name,
});
type.displayName = name;
}
},
});
}
return elementType;
}