【发布时间】:2021-02-26 16:29:36
【问题描述】:
我的 bestSellerDummy 数据不会改变,所以我想防止在父级重新渲染时重新渲染相同的 Product 子级。我曾尝试在父级中使用 useMemo 并在子级中使用 React.memo 但没有运气,每次父级重新渲染时它仍然显示日志“渲染产品组件..”。我在这里想念什么?请指教。
注意:每次我在 Product 组件中调用(CartContext 的)addToCart 函数时,都应该重新呈现父级。
我正在使用 CartContext,可能与此有关,我不确定。这里是沙盒:https://codesandbox.io/s/dazzling-moore-po1c6?file=/src/App.js
Home.tsx
const [bestSellerDummy] = useState(
[...new Array(5)].map((item, key) => ({
id: key,
imageUri:'https://1.jpg',
name: 'My Dummy 1',
price: 25,
})),
);
const bestSellers = useMemo(() => {
return bestSellerDummy.map((productDummy, key) => {
return (
<Product key={key} product={productDummy} />
);
});
}, [bestSellerDummy]);
return (
...
{bestSellers}
...
)
Product.tsx
const Product: FunctionComponent<IProductProps> = (
productProps,
) => {
...
console.log('Rendering Product component..');
...
}
export default React.memo(Product);
=== 编辑:我的答案版本 ===
终于!在玩过useCallback、useMemo、fast-memoize 插件之后。最适合我的是在上下文中使用useReducer,并用React.memo 包装昂贵的组件。我认为这是优化子组件最干净优雅的方式。工作沙箱在这里:https://codesandbox.io/s/eloquent-albattani-8x7h9?file=/src/App.js
【问题讨论】:
-
是什么原因导致父元素重新渲染?您能否通过 Codesandbox 提供一个可重现的最小示例?
-
@dongnhan Parent 预计每次我在 Product 组件中调用 addToCart 函数(属于 CartContext)时都会重新呈现。
-
你也可以通过第二个回调来比较React.memo中的
render的时间。如果您添加沙盒,那就太好了。否则很难从中分辨出来
标签: react-native react-hooks memoization use-reducer react-memo