在我的 React Native 應用程式中,我正在渲染一個陣列,并且我在該頁面中設定了切換按鈕。如果我更改任何一項,則陣列會更改并且組件會重新渲染,從而導致組件閃爍。我怎樣才能更改需要更改的專案并停止閃爍。
這是我當前的組件:
const Notifications = () => {
const dispatch = useDispatch();
const { t } = useTranslation('setting');
const notificationStatus = useSelector(getNotificationModeSelector);
const setNotificationStatus = useCallback(
(value: any) => dispatch(notificationsActions.setNotifications(value)),
[dispatch],
);
const getNotificationStatus = useCallback(
() => dispatch(notificationsActions.getNotifications()),
[dispatch],
);
const onToggleNotification = useCallback(async (item) => {
var changeParam = notificationStatus.map(obj =>
obj.id === item.id ? { ...obj, enabled: obj.enabled ==='1' ? '0' : '1' } : obj
);
setNotificationStatus(changeParam);
}, [notificationStatus, setNotificationStatus]);
useEffect(() => {
getNotificationStatus();
}, []);
console.log('Notifications Page',notificationStatus );
return (
<DesktopContainer>
<Container>
{notificationStatus.length !== 0 && notificationStatus.map((item)=>{
return(
<Wrapper key={Math. floor(Math. random() * 100)}>
<Title>{item.name}</Title>
<Switch
onColor={styles.SWITCH_COLOR}
offColor={styles.MEDIUM_GRAY}
isOn={item.enabled === '1' ? true : false}
size={
Dimensions.get('screen').width > styles.MIN_TABLET_WIDTH
? 'large'
: 'medium'
}
onToggle={()=>onToggleNotification(item)}
/>
</Wrapper>
)
})
}
</Container>
</DesktopContainer>
);
};
export default memo(Notifications);
uj5u.com熱心網友回復:
問題出在這一行:
<Wrapper key={Math. floor(Math. random() * 100)}>
您key應該始終是一個固定值。如果您的notificationStatus商品有唯一的 ID,那就太理想了。React 通過使用這些鍵優化其渲染周期;這就是允許它只改變它需要的東西的原因。由于所有映射的組件在每次渲染時都有新的鍵,React 會重新渲染它們。
有關更多資訊,請參閱本教程的“選擇密鑰”部分。 https://reactjs.org/tutorial/tutorial.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/437278.html
標籤:javascript 反应 反应式
上一篇:無法訪問該檔案,因為它正在被使用
