Задать вопрос

Как не менять позицию скролла при изменение состояния Redux?

есть Android приложение Туду со скролом, и когда я скролю вниз чуть ниже, ставлю галочку, то скролл возвращается вверх.

Вот код экрана на котором происходит скролл:
import React, { useEffect } from 'react';
import { Animated, StyleSheet, Text, View } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { IconButton, List, Divider } from 'react-native-paper';
import { useDispatch, useSelector } from 'react-redux';
import moment from 'moment';
import I18n from '../../libs/i18n'
import { openWinDelTodo } from '../../redux/actions/appActions';
import { cancelTodo, readyTodo } from '../../redux/actions/todoActions';
import { MaterialCommunityIcons, FontAwesome } from "../../libs/icons";
import settingLib from '../../libs/settingLib';
import { ColorIcon } from '../../libs/theme';
import RealmLib from '../../libs/realmLib';
import statLib from '../../libs/stat';
import { getStat } from '../../redux/actions/statActions';

function TodayView() {

    const dispatch = useDispatch();
    const navigation = useNavigation();
    const today = moment().format('DD-MM-YYYY').valueOf();
    const todayDate = moment(today, 'DD-MM-YYYY').valueOf();
    const todoes = useSelector(state => state.todo)
    const lists = useSelector(state => state.list)
    const d = new Date();
    const n = d.getDay();
    const theme = useSelector(state => state.app.theme)
    const typeTheme = settingLib.getTypeTheme(theme);


    const clickChackBox = (id, index, ready) => {
      if (!ready) {
        dispatch(readyTodo(index))
        RealmLib.todoReady(id)
      } else {
        dispatch(cancelTodo(index))
        RealmLib.todoCancel(id)
      }
      statLib.chackTodayStat()
      dispatch(getStat())
    }

    const sortTodoesToday = (todoesToday) => {

        todoesToday.sort((a, b) => parseTime(a.time) > parseTime(b.time) ? -1 : 1);

        todoesToday.sort((a, b) => !a.time ? -1 : 1);

        todoesToday.sort((a, b) => a.time && now > parseTime(a.time) ? 1 : -1);

        todoesToday.sort((a, b) => a.ready < b.ready ? -1 : 1);

        return todoesToday
    }

    let todoesToday = todoes.filter(todo => 
      (moment(todo.date, 'DD-MM-YYYY').valueOf() === todayDate
      && moment(todo.date, 'DD-MM-YYYY').valueOf() !== NaN)
      || (moment(todo.date, 'DD-MM-YYYY').valueOf() <= todayDate 
      && todo.deysWeek.indexOf(n) !== -1)
      || (todo.date === "" && todo.deysWeek.indexOf(n) !== -1))

    const now = moment();
    const parseTime = timeString => +moment(timeString, 'HH:mm')
    
    useEffect(() => {
      sortTodoesToday(todoesToday)
    }, [])

    const getNameList = (todo) => {
      if(todo.list === "0") {
        return I18n.t("otherList")
      } 
      const list = lists.filter(el => el.id === todo.list)[0]
      return list.name
    }

    const renderTodo = (item) => {

          const index = todoes.findIndex(el => el.id === item.id)

          let description = getNameList(item)
       
          return ( 
          <View key={item.id}>
            <List.Item
              key={item.id}
              titleStyle={(+parseTime(item.time) <= +parseTime(moment().format('HH:mm')) || item.ready === true) ? {"color": ColorIcon.chackboxReady(typeTheme)} : {"color": ColorIcon.chackboxNoReady(typeTheme)}}
              descriptionStyle={{"color": ColorIcon.descriptionColor(typeTheme, item.ready, +parseTime(item.time) <= +parseTime(moment().format('HH:mm')))}}
              title={item.title}
              description={((item.time !== "") ? moment(item.time, "HH:mm").format(I18n.t("formatTime")) : "--:--") + " (" + description + ")"}
              onPress={() => navigation.navigate('Todo', {title: item.title, todoId: item.id, id: index, type: "Todo"})}
              left={props => <IconButton 
                  {...props}
                  onPress={() => clickChackBox(item.id, index, item.ready, item)}
                  icon={
                      () => <MaterialCommunityIcons 
                      name={(item.ready === true) ? "checkbox-marked-circle-outline" : "checkbox-blank-circle-outline"} 
                      size={30} 
                      color={(+parseTime(item.time) <= +parseTime(moment().format('HH:mm')) || item.ready === true) ? ColorIcon.chackboxReady(typeTheme) : ColorIcon.chackboxNoReady(typeTheme)} />}
                  />}
              right={props => <IconButton
                  {...props}
                  onPress={() => dispatch(openWinDelTodo({title: item.title, todoId: item.id, index: index}))}
                  icon={() => <FontAwesome name="trash" size={25} color={(+parseTime(item.time) <= +parseTime(moment().format('HH:mm')) || item.ready === true) ? ColorIcon.treshReady(typeTheme) : "#ff221e"} />}
                  />}
          />
          <Divider />
          </View>
        )
    }

    const renderTodoes = () => {
      todoesToday = sortTodoesToday(todoesToday)
      // console.log(todoesToday)
      return todoesToday.map((item) => {
        return renderTodo(item)
      }) 
    }


    const styles = StyleSheet.create({
      container: {
        flex: 1,
        width: "100%",
        justifyContent: 'center', //Centered vertically
        alignItems: 'center', // Centered horizontally
      },
      text: {
        color: "#808080"
      },
      fab: {
        position: 'absolute',
        margin: 0,
        right: 0,
        bottom: 0,
      },
      block: {
        marginBottom: 85,
      },
    });

    return (
        <>
        {todoesToday.length !== 0 &&
            <Animated.ScrollView
              scrollEventThrottle={1}
              onScroll={Animated.event(
                [{ nativeEvent: { contentOffset: { y: new Animated.Value(0) } } }],
                { useNativeDriver: true } // <-- Add this
              )} >
              <View style={styles.block}>
                {renderTodoes()}
              </View>
              
            </Animated.ScrollView>
          }
  
          {todoesToday.length === 0 &&
  
            <View style={styles.container}>
              <Text style={styles.text}>{I18n.t("noTodayTodo")}</Text>
            </View>
          }
          </>
    )
}

export default React.memo(TodayView);
  • Вопрос задан
  • 80 просмотров
Подписаться 1 Простой Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы