反应挂钩useEffect缺少依赖项错误

时间:2020-10-18 07:59:01

标签: reactjs react-hooks use-effect

import React, { useState, useEffect, useRef } from 'react';
import styles from './TextAnimation.module.scss';

const TextAnimation = () => {
    const [typedText] = useState([
        "welcome to Byc",
        "change your life"
    ]);
    const [value, setValue] = useState();
    const [inType, setInType] = useState(false);
    
    const isMounted = useRef();
    
    let attachClasses = [styles.Blink];
    if(inType) {
        attachClasses.push(styles.Typing)
    }
    
    const typingDelay = 200;
    const erasingDelay = 100;
    const newTextDelay = 5000;

    let textArrayIndex = 0;
    let charIndex = 0;
    
    const type = () => {
        if(charIndex < typedText[textArrayIndex].length + 1) {
            if(isMounted.current) {
                setValue(typedText[textArrayIndex].substring(0, charIndex));
                charIndex ++;
                setTimeout(type, typingDelay);
            }
        } else {
            if(isMounted.current) {
                setInType(false);
                setTimeout(erase, newTextDelay);
            }
        }
    };

    const erase = () => {
        if(charIndex > 0) {
            if(isMounted.current) {
                setValue(typedText[textArrayIndex].substring(0, charIndex - 1));
                charIndex --;
                setTimeout(erase, erasingDelay);
            }
        } else {
            if(isMounted.current) {
                setInType(false);
                textArrayIndex ++;
                if(textArrayIndex >= typedText.length) {
                    textArrayIndex = 0;
                }
                setTimeout(type, newTextDelay - 3100);
            }
        }
    };
    
    useEffect(() => {
        isMounted.current = true;
        type();
        return () => {
            isMounted.current = false;
        }
    }, [])

    return (
        <div className={styles.TextAnimation}>
            <span className={styles.Text} >{value}</span><span className=        
            {attachClasses.join(' ')} >&nbsp;</span>
        </div>
    );
};

export default TextAnimation;

您好,我正在尝试制作文字动画,但我收到了此消息...

反应挂钩useEffect缺少依赖项:'type'。包括它或删除依赖项数组

我尝试像这样在[]中输入put

useEffect(() => {

 ...

}, [type])

但是没有用 我试图以多种方式搜索解决方案 但我不能 有什么可以帮助我的吗? 谢谢

0 个答案:

没有答案