React bug:同时使用setState - setInterval
我有一个小的react程序。单击start后,屏幕上会有一个球向下移动。当它到达某个点时,它应该消失并从头开始。然而,它并不像预期的那样工作。该运动是由setInterval函数和状态递增位置创建的。然而,这很奇怪。球在移动,但在制造console.log的地方,state.position始终为0。它应该是状态的当前值。为什么一直都是0?最后,我不应该改变状态格式。我知道这不是通常的状态格式,但出于其他原因,我需要这种格式。
import React, { useState } from 'react'
function BallMoving () {
const [state, setState] = useState({
intro: true,
position: 0
})
const updateMoving = () => {
setState(prevState => ({ ...prevState, intro: false }))
setInterval(() => {
console.log(state.position)
if (state.position === 50) {
setState(prevState => ({ ...prevState, position: 0 }))
}
setState(prevState => ({ ...prevState, position: prevState.position + 1 }))
}, 30)
}
if (state.intro) {
return (
<div>
<button onClick={() => updateMoving()}>Start</button>
</div>
)
}
return (
<div style={{ width: '100px', height: '100px', position: 'relative', border: '1px solid black' }}>
<div style={{ position: 'absolute', top: state.position + 'px', left: '10%', width: '10px', height: '10px', backgroundColor: 'red' }} />
</div>
)
}
转载请注明出处:http://www.fymidi.com/article/20230526/1107885.html