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>
);
};
该代码运行完美。只是一个交通灯会改变其颜色。但是我首先需要使这三个指示灯保持活动状态五秒钟,并且只有一次。我不知道该怎么做。
您可以添加一个附加状态变量,以表示TrafficLight是否正在工作或处于某种初始状态。然后,您只需要以与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>
);
};