在昨天的工作面试中,我被问到一个问题:What are the internal implementation differences between PureComponent and Component in React
,而我对该问题的了解不足使我的面试陷入困境。
我知道它们之间的详细区别,包括React文档中的所有内容以及何时以及如何使用它们,但是我不知道它们在React的源代码中的实现。
您能否给我一些有关该问题的简短摘要,以及一些有关如何深入了解React的源代码以获取更深入知识的建议?
答案 0 :(得分:2)
除了常规组件不会为您处理生命周期方法shouldComponentUpdate()
之外,纯组件和常规组件实际上是相同的。在纯组件中,当props或状态改变时,纯组件将通过对props和state进行浅比较来自动检查以查看组件是否需要重新渲染。
常规组件不会执行此比较(除非您自己在shouldComponentUpdate()
中指定一些比较)。
您可以找到有关差异here的出色文章。以及实际的源代码差异here
这是实际的代码差异。
if (ctor.prototype && ctor.prototype.isPureReactComponent) {
return (
!shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState)
);
}
答案 1 :(得分:1)
唯一的区别是PureComponent
具有shouldComponentUpdate
的预定义。您可以在当前的react code on github中看到它:
if (ctor.prototype && ctor.prototype.isPureReactComponent) {
return (
!shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState)
);
}
它只是检查道具和状态是否浅浅。