简体   繁体   English

在 React 中的计时器上的 switch 语句

[英]Switch statement on a timer in React

Trying to automatically increment the index of my switch statement so my site will automatically switch different elements out.尝试自动增加我的 switch 语句的索引,以便我的网站会自动切换不同的元素。

Trying to achieve this using:尝试使用以下方法实现此目的:

export default function MainComponent(props) {
  let index = 0;

  switch (index) {
    case 0:
      counter++;
      console.log(index)
      return (
       //ELEMENT 1
      );
    case 1:
      index++;
      console.log(index)
      return (
      //ELEMENT 2
      );
    case 2:
      index++;
      console.log(index)
      return (
        ELEMENT 3
      );
    case 3:
      index++;
      console.log(index)
      return (
        //ELEMENT 4
      );

    default:
      return (
     null
     )

I can see that the index increments in the console so I don't understand why my switch state isn't switching to the next element.我可以看到控制台中的索引增加了,所以我不明白为什么我的开关 state 没有切换到下一个元素。

Any help appreciated任何帮助表示赞赏

If I understand you correctly you need to use hooks for the state.如果我理解正确,您需要使用 state 的挂钩。 Otherwise, React won't rerender your component.否则,React 不会重新渲染你的组件。

import { useCallback, useState } from "react";

export default function App() {
    let [index, setIndex] = useState(0)
    let increment = useCallback(() => {
      setIndex(index => index + 1);
    }, [setIndex])
  
    switch (index) {
      case 0:
        increment()
        console.log(index)
        return 1
      case 1:
        increment()
        console.log(index)
        return 2
      case 2:
        increment()
        console.log(index)
        return 3
      case 3:
        increment()
        console.log(index)
        return 4
      default:
        return 'default'
    }
}

But renders happen quickly.但是渲染发生得很快。 You will need some timeouts to see different cases on the screen您将需要一些超时才能在屏幕上看到不同的情况

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM