首页 > 解决方案 > 根据将下一个状态与前一个状态进行比较来更新状态 - 钩子?

问题描述

我有拖车标签,基于滑动下一个/上一个视图激活,

我有不可接受的滑动,当我滑动到下一个视图时,我会更新索引以激活下一个选项卡,而且效果很好,

但是,如果我在 Tab 0 中并滑动两次到下一个,我会遇到意外的行为,它会激活上一个 Tab

如果我在 Tab 0 中并滑动两次到下一个,我希望只激活 Tab 0 等等,

因此,onScrollEndDrag如果当前活动选项卡为 0,则在我更新选项卡索引时更新为 1,否则更新为 0

但是当我得到以前的状态并与当前状态进行比较时效果不佳或者我认为它很糟糕。

我不知道我怎么能期望用户刷卡所以我不知道如何获得下一个状态:\

我希望任何人都明白我在这种情况下的确切含义。

这是一个GIF,请检查它!

代码片段

const Tabs = [
  {
    name: 'opened',
  },
  {
    name: 'closed',
  },
];
const AppointmentScreen = () => {
  const scrollRef = useRef(null);
  const [currentIndex, setCurrentIndex] = useState(0);
 
 return (
    <View style={styles.appointmentsTabs}>
    {Tabs.map(({ name }, tabIndex) => (
     <TouchableOpacity
       key={tabIndex}
       onPress={() => {
        if (tabIndex === currentIndex) {
          return;
        }
        if (scrollRef.current) {
          scrollRef.current.scrollTo({
            x: tabIndex === 0 ? width : width * (tabIndex - 1),
            y: 0,
            animated: true,
          });
          setCurrentIndex(currentIndex === 1 ? 0 : 1);
        }

      }}
      delayPressIn={0}
      style={[
        styles.appointmentsBox,
        {
          backgroundColor: tabIndex === currentIndex ? '#000' : '#fff',
        },
      ]}>
      <Text
        style={[
          styles.appointmentText,
          {
            color: tabIndex === currentIndex ? '#fff' : '#000',
          },
        ]}>
        {name}
      </Text>
    </TouchableOpacity>
  ))}
</View>
  <Animated.ScrollView
    ref={scrollRef}
    showsHorizontalScrollIndicator={false}
    bounces={false}
    decelerationRate="fast"
    snapToInterval={width}
    onScrollEndDrag={() => {
      if (scrollRef.current) {
        setCurrentIndex((prevState) => {
          console.log('prevState: ', prevState);
          console.log('currentIndex: ', currentIndex);
          return prevState === 0 ? 1 : 0;
        });
      }
    }}
    horizontal>
    <OpenedAppointments />
    <ClosedAppointments />
  </Animated.ScrollView>
);
}

演示

标签: javascriptreactjsreact-nativereact-hooks

解决方案


推荐阅读