React Native ужасная производительность после реакции hooks + стрелка - PullRequest
0 голосов
/ 24 марта 2020

Я думаю, что в заголовке почти все сказано, но я все равно дам резюме.

Это второй проект, над которым я работал, реагирую на натив, но на этот раз я решил реализовать что-то новое, как реагировать на встроенные хуки и функции стрелок (которые я раньше не реализовывал), поэтому вместо рендеринга экрана с типичными

 export default class 'ScreenName' extends Component {
  constructor(props){
   super(props);

   this.state = {'states here'}
  }

  render(){
   return(
    'code here'
   );
  }
}

я сделал это так

const 'ScreenName' = () => {
 const [stateName, setName] = useState('');
 'other states here'

 return(
  'code here'
 );
}

Дело в том, что мое приложение стало болезненным для навигации, и нет, это не проблема навигации, я отключил анимационные переходы, и каждый экран медленный, даже те, с небольшим количеством изображений или списков, вот пример один из моих экранов, возможно, самый медленный до сих пор.

import * as React from 'react';
import {View, Text, StatusBar, RefreshControl, Image, ScrollView, TouchableOpacity, ImageBackground} from 'react-native';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import {Header, Overlay} from 'react-native-elements';
import {ListItem} from 'react-native-elements';
import Images from '../../Assets/values/images';
import Colors from '../../Assets/values/colors';
import DataManager from '../../../Util/CrossUtils/DataManager';
import VacationHistoryBusiness from '../../../Template/ViewModel/Vacation/VacationHistory/VacationHistoryBusiness';
import Constants from '../../Assets/values/styles/Vacation/VacationStyleConstants';
import ModalSuccessRequest from '../../Assets/Components/ModalSuccessRequest';
import styles from '../../Assets/values/styles/Vacation/VacationStyle';
import dayjs from 'dayjs';

const VacationScreen = (props) => {
  React.useEffect(() => {
    VacationHistoryBusiness.GetInstance().getListVacation;
    VacationHistoryBusiness.GetInstance().getLastObjectRequestVacation;
  })

  function _onRefresh() {}

  const [isVisible, setVisible] = React.useState(false);
  const [isRefreshing, setRefreshing] = React.useState(false);
  const listItem = [{id: 0,titulo: '07/12/2020',subtitulo: '07/23/2020',estado: 'Etiqueta'},{id: 1,titulo: '02/12/2020',subtitulo: '02/14/2020',estado: 'Etiqueta'},{id: 2,titulo: '11/04/2020',subtitulo: '11/08/2020',estado: 'Etiqueta'},{id: 3,titulo: '08/07/2020',subtitulo: '08/12/2020',estado: 'Etiqueta'}];

  return (
    <>
      <StatusBar translucent backgroundColor="transparent" />
      <Header
        backgroundImage={Images.header_nav}
        backgroundImageStyle={styles.HeaderImagen}
        rightComponent={
          <TouchableOpacity onPress={() => props.navigation.navigate('Login')}>
            <Image source={Images.logout}/>
          </TouchableOpacity>
        }
        centerComponent={{text: Constants.HeaderTitle, ellipsizeMode: 'clip', style: styles.HeaderVacaciones }}
        placement='left'/>
      <View style={styles.ContainerBackground}>
        <KeyboardAwareScrollView>
        <ImageBackground style={styles.VacacionesBackground} source={Images.img_vacaciones}>
          <View style={styles.RightComponent}>
            <TouchableOpacity onPress={() => setVisible(true)}>
            <View style={styles.CenterInside}>
              <Image style={styles.DiasVacacionesComponent} source={Images.dias_vacaciones}/>
              <Text style={styles.DiasDisponiblesTitulo}>12</Text>
              <Text style={styles.DiasDisponiblesSubtitulo}>{Constants.DiasDisponiblesSubtitulo}</Text>
              <Text/>
            </View>
            </TouchableOpacity>
          </View>
        </ImageBackground>
        <ScrollView>
        {
          //DataManager.ObjectLastRequestVacation !== null ?
          listItem.length === 0 ? null :
          <View style={styles.Left}>
            <Text style={styles.ProximasVacacionesTitulo}>{Constants.ProximasVacacionesTitulo}</Text>
          </View>
          //: null
        }
        {
          //DataManager.ObjectLastRequestVacation !== null ?
          listItem.length === 0 ?
          <View style={styles.SinSolicitudes}>
            <Text style={styles.SinSolicitudesText}>{Constants.SinVacacionesDisponibles}</Text>
          </View>
          //: null
          :
          listItem.slice(0,1).map(value => (
            <TouchableOpacity onPress={() => props.navigation.navigate('VacationsDetail')}>
              <ListItem
                topDivider={true}
                bottomDivider={true}
                containerStyle={styles.ContainerLista}
                titleStyle={styles.TituloLista}
                subtitleStyle={styles.SubtituloLista}
                key={value.id}
                leftIcon={<Image resizeMode={'contain'} style={styles.LeftIcon} source={Images.vacaciones_ico}/>} 
                rightIcon={<Image resizeMode={'contain'} width={30} source={Images.chevron_right}/>} 
                title={`Desde ${dayjs(value.titulo).format('DD/MM')} hasta ${dayjs(value.subtitulo).format('DD/MM')}`}
                subtitle={
                  <View style={styles.BadgeEstado}>
                    <Text style={styles.SubtituloLista}>{value.estado}</Text>
                  </View>
                }/>
            </TouchableOpacity>
          ))
        }
        {
          listItem.length === 0 ? null :
          <View style={styles.Left}>
            <Text style={styles.ProximasVacacionesTitulo}>{Constants.VacacionesAnterioresTitulo}</Text>
          </View>
        }
        {
          listItem.length === 0 ? null : 
          listItem.slice(1).map(value => (
            <TouchableOpacity onPress={() => props.navigation.navigate('VacationsDetail', {'Historico': true})}>
              <ListItem
                topDivider={true}
                bottomDivider={true}
                containerStyle={styles.ContainerLista}
                titleStyle={styles.TituloLista}
                subtitleStyle={styles.SubtituloLista}
                key={value.id}
                leftIcon={<Image resizeMode={'contain'} style={styles.LeftIcon} source={Images.vacaciones_ico}/>}
                rightIcon={<Image resizeMode={'contain'} width={30} source={Images.chevron_right}/>} 
                title={`Desde ${dayjs(value.titulo).format('DD/MM')} hasta ${dayjs(value.subtitulo).format('DD/MM')}`}/>
            </TouchableOpacity>
          ))
        }
        </ScrollView>
        <View style={styles.BottomPush}/>
        </KeyboardAwareScrollView>
        <TouchableOpacity style={styles.ButtonSolicitarVacaciones} onPress={() => props.navigation.navigate('VacationsRequest')}>
            <Text style={styles.TextSolicitarVacaciones}>{Constants.SolicitarVacaciones}</Text>
        </TouchableOpacity>
        <Overlay
          onBackdropPress={() => setVisible(false)}
          isVisible={isVisible}
          windowBackgroundColor={Colors.background_white}
          borderRadius={1}
          width='auto'
          height='auto'>
          <ModalSuccessRequest estado={isVisible} desde={dayjs('07/12/2020').format('DD/MM/YYYY')} hasta={dayjs('07/23/2020').format('DD/MM/YYYY')}/>
        </Overlay>
      </View>
    </>
  );
}

export default VacationScreen;
...