当React Native中的一个项目发生更改时,数组数据会闪烁



在我的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);

问题就在这一行:

<Wrapper key={Math. floor(Math. random() * 100)}>

您的key应该始终是一个固定值。如果你的notificationStatus物品有一个唯一的ID,那就太理想了。React通过使用这些关键帧来优化其渲染周期;这使得它只能改变它需要的东西。由于所有映射组件在每个渲染上都有新的关键帧,React会重新渲染所有组件。

参见";选择一把钥匙"有关详细信息,请参阅本教程的部分。https://reactjs.org/tutorial/tutorial.html

最新更新