[英]Why does a conditionally rendered React component flicker on refresh but not an inline version of the same component?
我難住了。 為什么一個閃爍,另一個不閃爍?
這是一個強制刷新屏幕的人為示例。
有關useInterval
和useForceUpdate
掛鈎,請參閱此 Expo Snack上的完整源代碼。
屏幕
代碼
const App = () => { const forceUpdate = useForceUpdate(); useInterval(() => { forceUpdate(); }, 1000); const imageSource = { uri: 'https://images.unsplash.com/photo-1485832329521-e944d75fa65e?auto=format&fit=crop&w=1000&q=80&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D', }; const shouldRenderImage = true; const MyImage = () => ( <> {shouldRenderImage && <Image style={styles.image} source={imageSource} />} </> ); return ( <View style={styles.container}> <Text style={styles.paragraph}>Conditional Inside Component</Text> <MyImage /> <Text style={styles.paragraph}>Conditional Render Component</Text> <> {shouldRenderImage && ( <Image style={styles.image} source={imageSource} /> )} </> </View> ); };
這是因為您正在使用功能組件。所以每次您的狀態更改時,您的所有功能都會再次初始化。 因此,每當狀態發生變化時,您的 Image 組件將重新初始化,(它將再次安裝)
const MyImage = () => (
<>
{shouldRenderImage && <Image style={styles.image} source={imageSource} />}
</>
);
為了盡量減少每次重新渲染時的重新初始化,我們可以使用useCallback
鈎子。
import React, {useCallback} from 'react';
const MyImage = useCallback(() => (
<>
{shouldRenderImage && <Image style={styles.image} source={imageSource} />}
</>
),[shouldRenderImage]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.