React setStates只更新一次状态并重置它



你好,我对React有点陌生我试着做一个类似蛇的游戏,但我在动作上很吃力。

x和y的值从来没有真正改变过,他只能移动一个类似的1格单元格,但当我按下另一个键时,他会转到起始位置,并向另一个方向移动1格单元格。。我错过了什么?

function App() {
const [_x, setX] = useState(0);
const [_y, setY] = useState(0);
let lastPressedKey = '';
let gameTicker = null;

function triggerMovement(x, y) {
if (lastPressedKey === 100)
move(10, 0);
if (lastPressedKey === 97)
move(-10, 0);
if (lastPressedKey === 119)
move(0, 10);
if (lastPressedKey === 155)
move(0, -10);
}
function move(x, y){
console.log(lastPressedKey);
console.log(x, _x, y, _y);
setX(_x + x);
setY(_y + y);
}
function handleKeyEvent(event) {
lastPressedKey = event.keyCode;
}
function startTimer() {
gameTicker = setInterval(triggerMovement, 1000);
}
function clearTimer() {
clearInterval(gameTicker)
}
const element = (
<div>
<Screen farbe="darkslategray">
<Snake x={_x} y={_y} farbe="red"/>
</Screen>
<button onClick={startTimer} style={{
bottom: 5,
position: 'absolute'
}}>
Start Game
</button>
<button onClick={clearTimer} style={{
bottom: 5,
left: 625,
position: 'absolute'
}}>
StopGame
</button>
</div>
)
window.addEventListener('keypress', handleKeyEvent, true);
return element;
}
function Snake(props){
const [x, setX] = useState(250);
const [y, setY] = useState(250);
let speed = props.speed;
const element = (
<div style={{
width: 10,
height: 10,
backgroundColor: props.farbe,
position: 'absolute',
left: props.x,
bottom: props.y
}}>
</div>
)
return element;
}

真的很想摆脱这件事,但我想让这条蛇动起来,因为今天早上我知道我在这里错过了什么。

控制台日志总是

10, 0 , 0 , 0
10, 0 , 0 , 10
10, 0 , 0 , 0 ... 

这是因为过时的闭包

此处

function move(x, y){
console.log(lastPressedKey);
console.log(x, _x, y, _y);
setX(_x + x);
setY(_y + y);
}

_x_y引用了在其中调用startTimer函数的渲染中的值。

您可以使用setState的函数形式来避免这个问题:

setX(ps => ps+x)

最新更新