Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

81
Views
React setStates solo actualiza el estado una vez y lo reinicia

Hola, soy un poco nuevo en React. Estoy tratando de hacer un juego de serpientes, pero estoy luchando con el movimiento.

los valores x e y nunca cambian realmente, solo puede mover una celda similar a 1, pero cuando presiono otra tecla, simplemente va a la posición inicial y va 1 celda en la otra dirección. ¿Qué me estoy perdiendo?

 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; }

Realmente estoy tratando de respaldar esto, pero estoy tratando de hacer que esta serpiente se mueva desde esta mañana, no sé lo que me estoy perdiendo aquí.

Los registros de la consola siempre son

 10, 0 , 0 , 0 10, 0 , 0 , 10 10, 0 , 0 , 0 ...
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Es por cierres obsoletos .

Aquí

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

_x y _y son valores de referencia del renderizado en el que llamaste a la función startTimer .

Puede usar la forma funcional de setState para evitar este problema:

 setX(ps => ps+x)
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!