[英]Change text every 3 seconds React useEffect
I'm trying to change my text every 3 seconds using useEffect() and setInterval().我正在尝试使用 useEffect() 和 setInterval() 每 3 秒更改一次文本。 Right now it only changes the text ONE time then it doesn't change it anymore.
现在它只更改一次文本,然后不再更改它。 What am i doing wrong?
我究竟做错了什么?
EDIT: I'm using the library "react-spring"编辑:我正在使用库“react-spring”
const [toggle, setToggle] = useState(false)
useEffect(() => {
setInterval(() => {
switch (toggle) {
case false: setToggle(true)
break;
case true: setToggle(false)
break;
}
}, 3000);
}, [])
{transitions.map(({ item, props }) => item
? <animated.div style={props}>Text that changes #1</animated.div>
: <animated.div style={props}>Text that changes #2</animated.div>)}
Solution:解决方案:
useEffect(() => {
const intervalID = setTimeout(() => {
setToggle((toggle) => !toggle)
}, 3000);
return () => clearInterval(intervalID);
}, []);
Important points:要点:
[]
) should be empty.[]
)应该是空的。 This way you ensure that you're gonna execute this effect only on the initial mounting of the component.toggle
in the dependency array, you will run this effect every time the variable changes thus effectively making YET ANOTHER interval on every 3 seconds.toggle
,您将在每次变量更改时运行此效果,从而有效地每 3 秒产生一次间隔。 If you did supply a clean-up function, this would still work but it would be more like a setTimeout
.setTimeout
。 However, in your case(without a clean-up function), this will simply introduce infinite number of intervals which will compete with each other.setToggle
instead of a simple value.setToggle
而不是简单的值。 This ensures that you're using the most current state for the update and not the stale one in the closure.false
to true
and this will repeat forever, leaving you with a "constant" true
value.false
更新为true
,这将永远重复,为您留下一个“恒定”的true
值。useEffect
to clear the interval on component dismount.useEffect
以清除组件卸载的间隔。 This is very important as skipping this part will introduce memory leaks and also bugs as you'll try to update a component even after its dismount from the DOM. Try this way试试这个方法
useEffect(() => {
setTimeout(() => setToggle((prevToggle) => !prevToggle), 3000);
}, [toggle]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.