Как остановить setInterval в компоненте useEffect / react - PullRequest
0 голосов
/ 28 мая 2020
• 1000 Я могу считать, но мне нужно, чтобы счетчик остановился, когда «событие» закончится.

enter image description here

Мой код ниже, есть ли у кого-нибудь предложения по его работе или альтернативное решение?

/* eslint-disable react/jsx-one-expression-per-line */
/* eslint-disable react-native/no-color-literals */
/* eslint-disable react-native/no-unused-styles */
// @flow
import React, { useState, useEffect, useCallback } from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
import moment from 'moment';
import Countdown from 'react-countdown';

const styles = StyleSheet.create({
    container: {
        flexDirection: 'row',
    },
    containerWrapper: {
        borderColor: '#FFFFFF',
        borderRadius: 2,
        borderWidth: 2,
        flexDirection: 'row',
        maxWidth: '60%',
        padding: 5,
    },
    containerWrapperRed: {
        borderColor: '#FF3264',
        borderRadius: 2,
        borderWidth: 2,
        flexDirection: 'row',
        maxWidth: '60%',
        padding: 5,
    },
    redText: {
        color: '#FF3264',
        fontFamily: 'Helvetica Neue',
        fontSize: 16,
        fontStyle: 'normal',
        fontWeight: 'bold',
        lineHeight: 22,
    },
    text: {
        color: '#FFF',
        fontSize: 30,
        paddingRight: 5,
    },
    whiteText: {
        color: '#FFFFFF',
        fontFamily: 'Helvetica Neue',
        fontSize: 16,
        fontStyle: 'normal',
        fontWeight: 'bold',
        lineHeight: 22,
        paddingRight: 5,
    },
});

type Props = {
    hours: string,
    minutes: string,
    seconds: string,
    completed: boolean,
};

const VodCounter = () => {
    const [seconds, setSeconds] = useState(0);
    const [isActive, setIsActive] = useState(false);
    const [isCountingDown, setCountingDown] = useState(true);

    useEffect(() => {
        let interval = null;
        if (isActive) {
            interval = setInterval(() => {
                setSeconds(seconds => seconds + 1);
            }, 1000);
        } else if (!isActive && seconds !== 0) {
            clearInterval(interval);
        }
        return () => clearInterval(interval);
    }, [isActive, seconds]);

    useEffect(
        interval => {
            let timer = null;
            if (isActive) {
                timer = setTimeout(() => {
                    clearInterval(interval);
                }, 5000);
            }
            return () => clearTimeout(timer);
        },
        [isActive],
    );

    const renderer = ({ hours, minutes, seconds, completed }: Props) =>
        completed && isCountingDown ? (
            ((setCountingDown(false), setIsActive(true), console.log('finished')), null)
        ) : (
            <Text style={styles.whiteText}>
                ALGAB {hours}:{minutes}:{seconds}
            </Text>
        );

    return (
        <View style={isCountingDown ? styles.containerWrapper : styles.containerWrapperRed}>
            {isCountingDown ? (
                <Countdown date={Date.now() + 5000} renderer={renderer} />
            ) : !isCountingDown && isActive ? (
                <Text style={styles.redText}>Praegu Live {seconds}s</Text>
            ) : !isCountingDown && !isActive ? (
                <Text>finished</Text>
            ) : null}
        </View>
    );
};

export default VodCounter;
...