简体   繁体   English

在 React Native 中更改一项时数组数据闪烁

[英]Array data flickers when one item is changed in React Native

In my React Native app, i am rendering an array and i have toggle buttons set in that page.在我的 React Native 应用程序中,我正在渲染一个数组,并且在该页面中设置了切换按钮。 If i change any one item, the array gets changed and the component rerenders which result in flickering of the component.如果我更改任何一项,数组就会更改并且组件会重新呈现,从而导致组件闪烁。 How can i just change the item that's needed to be changed and stop the flickering.我怎样才能改变需要改变的项目并停止闪烁。

Here's my current component:这是我当前的组件:

 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);

The issue is on this line:问题出在这一行:

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

Your key should always be a fixed value.您的key应始终为固定值。 If your notificationStatus item has a unique ID, that's ideal.如果您的notificationStatus项目有一个唯一的 ID,那是理想的。 React optimizes its render cycle by using these keys; React 通过使用这些键来优化它的渲染周期; that's what allows it to only change what it needs.这就是允许它只改变它需要的东西的原因。 Since all of your mapped components have new keys on each render, React re-renders them all.由于所有映射的组件在每次渲染时都有新键,因此 React 会重新渲染它们。

See the "Picking a Key" section of this tutorial for more.有关更多信息,请参阅本教程的“选择密钥”部分。 https://reactjs.org/tutorial/tutorial.html https://reactjs.org/tutorial/tutorial.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM