我想知道在组件之外定义元素是否可以。就这样吧
const Element = <Component/>
const App = () => {
return <MemoizedParentComponent>{Element}</MemoizedParentComponent/>
}
所以,我想这样做的原因是因为
MemoizedParentComponent
在底层使用了 React.memo
,如果我们直接将 <Component/>
作为 Children 属性传递,那么每当渲染 App
组件时,它都会导致重新渲染(如果例如,它有一些状态)。
所以基本上,据我所知,有两种选择可以支持正常记忆:
Element
组件内的 useMemo
中定义 App
App
组件之外,如上例所示。在组件之外定义元素是否存在任何潜在风险或者这是一个合法的选择?
这两个选项似乎都有效,但它们之间有一个可能很重要的区别:在组件外部定义的内容在该组件的实例之间共享,就像 Java 中的静态字段,而
useMemo
中包装的内容是私有的。
是否重要取决于你要创建多少个
App
实例 - 如果只有一个也没关系,如果更多则可能有意义 - 这又取决于 React 是否修改 elements (当您像这样调用组件时返回的对象:<Component/>
)。不幸的是我不知道它是否有效,这是一个实现细节,我们不应该依赖它。
总结一下:使用
Rect.useMemo
只是为了安全。
或者您可以使用类似线程中提供的解决方案之一,请查看:如何将 React.memo 与包含子组件的组件一起使用 但要小心:我认为接受的答案不正确,但我懒得去实际检查。我喜欢 Maxime Bret 提供的建议为
arePropsEqual
的 React.memo
实现自定义 MemoizedParent
功能 - 如果您可以修改它,这就是我可能会做的。
可以这样实现:
/**
* Replicates default behaviour os `React.memo` for everything except
* for `children` which are ignored.
*/
function arePropsEqual(prevProps, newProps) {
for (const [key, prevValue] of Object.entries(prevProps)) {
if (key === 'children') {
continue; //ignore if children changed
}
const newValue = newProps[key];
//comparing by `Object.is` is the default behaviour used by React.memo
if (!Object.is(prevValue, newValue))
return false;
}
return true;
}
只要孩子们没有道具,这就会很酷。如果他们愿意,就需要更深入地了解
prevProps['children']
与 newProps['children']
的对比。