【问题标题】:set interval in react repeating itself设置重复反应的间隔
【发布时间】:2021-05-14 18:19:25
【问题描述】:

我正在尝试为我的作品集制作一个打字动画,我有一系列想要输入的单词,我试着让它每 5 秒左右更新一次单词。所以我设置了一个间隔来更新一个 useState 来更新将要显示的单词

const [displayTyped, setDisplayTyped] = useState("Developer");
const typedWords = ['Developer', 'Designer', 'Freelancer', 'Photographer'];
let currentWord = 0;

setInterval(() => {
   setDisplayTyped(typedWords[currentWord])

   if(currentWord < 3) {
     currentWord++;
   } else {
     currentWord = 0;
   };     
}, 5000);

但是当我这样做时,它会更新两次并像开发人员一样停留,然后我等待的时间越长,它会像 6 次一样经历所有这些并立即更改它,我不知道是谁在这样做 当我console.log(currentWord) 它显示它发生了两次所以我认为 useState 正在重新加载页面并将单词设置为默认值

【问题讨论】:

    标签: reactjs use-state


    【解决方案1】:

    每次渲染时,都会创建一个新的setInterval,目前还没有清除它的机制。我可能会做的是

    useEffect(() => {
        let currentWord = 0;
        const interval = setInterval(() => {
            setDisplayTyped(typedWords[currentWord]);
            currentWord = ++currentWord % 4;
        }, 5000);
        return () => clearInterval(interval);
    }, []);
    

    【讨论】:

    • 有什么使用效果我还没学会那个有什么作用
    • useEffect 将运行其中的代码一次,然后仅在更新依赖数组中的项目时再次运行。在这种情况下,我们传入一个空的[],因此它将运行代码一次。当组件卸载时,它将运行useEffect 返回的任何内容,在这种情况下清除间隔。
    • 我的另一个问题是++currentWord % 4 是如何工作的,因为我想不出我所知道的任何方法
    • 4 % 4 === 0,所以currentWord = ++currentWord % 4 会增加它,但如果它变成4,它会变成0
    【解决方案2】:

    试试这个:

    const [displayTyped, setDisplayTyped] = useState("Developer");
    const typedWords = ['Developer', 'Designer', 'Freelancer', 'Photographer']; // <- move this outside of the component if it's just static.
    const [currentWord, setCurrentWord] = useState(0);
    
    useEffect( () => {
        function updateWord() {
            setDisplayTyped(typedWords[currentWord])
            if(currentWord < 3) {
                setCurrentWord(currentWord + 1);
            } else {
                setCurrentWord(0);
            };
        }
        setTimeout(updateWord, 5000);
    }, [currentWord])
    

    由于 React 会在每次状态更新时渲染这个组件,所以你不需要使用setInterval。每次渲染都会调用 5 秒 setTimeout 调用。 currentWord 将更新,因此 useEffect 将运行,setDisplayTyped 将被调用。

    这里是一个沙盒链接来展示效果: codesandbox.io

    【讨论】:

      猜你喜欢
      • 2023-01-12
      • 2020-12-21
      • 1970-01-01
      • 2016-07-25
      • 1970-01-01
      • 1970-01-01
      • 2019-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多