在 React Hooks 中使用 SetTImeout 的交通灯

TrafficLight using SetTImeout and ReactHooks

const lightDurations = [ 5000, 2000, 1000];

const TrafficLight = ({ initialValue }) => {
  const [colorIndex, setColorIndex] = useState(initialValue);

  useEffect(() => {
    const timer = setTimeout(() => {
      setColorIndex((colorIndex + 1) % 3);
    }, lightDurations[colorIndex]);
    return () => {
      clearTimeout(timer);
    };
  });

  return (
    <div className="traffic-light">
      <Light color="#f00" active={colorIndex === 0} />
      <Light color="#ff0" active={colorIndex === 2} />
      <Light color="#0c0" active={colorIndex === 1} />
    </div>
  );
};

代码完美运行。它只是一个改变颜色的交通灯。但首先我需要三盏灯亮起五秒钟,而且只亮一次。我不知道该怎么做。

您可以添加一个额外的状态变量来表示交通信号灯是在工作还是处于某种初始状态。然后你只需要以与 colorIndex.

类似的方式切换此状态
const initialDelay = 5000;

const TrafficLight = ({ initialValue }) => {
  const [colorIndex, setColorIndex] = useState(initialValue);
  const [isStarted, setIsStarted] = useState(false);

  useEffect(() => {
    const timer = setTimeout(() => {
      setIsStarted(true);
    }, initialDelay);
    return () => {
      clearTimeout(timer);
    };
  }, []); // note [] - it makes it run once

  useEffect(() => {
    if (!isStarted) {
      return;
    }
    const timer = setTimeout(() => {
      setColorIndex((colorIndex + 1) % 3);
    }, lightDurations[colorIndex]);
    return () => {
      clearTimeout(timer);
    };
  });

  return (
    <div className="traffic-light">
      <Light color="#f00" active={!isStarted || colorIndex === 0} />
      <Light color="#ff0" active={!isStarted || colorIndex === 2} />
      <Light color="#0c0" active={!isStarted || colorIndex === 1} />
    </div>
  );
};