Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

127
Vistas
React hook setState: configuración de una matriz (tutorial de React Tic Tac Toe pero con ganchos)

He estado tratando de seguir el tutorial de reaccionar tic tac toe, pero para usar componentes funcionales en lugar de componentes de objetos. Todo funciona maravillosamente hasta la parte de retroceso.

Reduje el problema al hecho de que en mi función handleClick setHistory(hist) en realidad no está cambiando el estado del historial. hist es una matriz de matrices aquí.

(Solo incluyo el componente del juego por razones de brevedad, pero si necesita el archivo completo, hágamelo saber).

 const Game= () => { const [xIsNext, setXIsNext] = useState(true); const [history, setHistory] = useState(Array(Array(9).fill(null))); const [stepNumber, setStepNumber] = useState(0); function handleClick(i) { const hist = history.slice(0, stepNumber+1); console.log(hist) setHistory(hist); console.log("in handleClick - log 1 - history size = "+ history.length) const currentBoard = [...history[stepNumber]]; const winner = calculateWinner(currentBoard); if (winner || currentBoard[i]) return; currentBoard[i] = xIsNext ? "X" : "O"; setHistory(history.concat([currentBoard])); setStepNumber (stepNumber + 1) setXIsNext(!xIsNext); } function jumpTo(move) { setXIsNext(move % 2 == 0) setStepNumber(move) } const currentBoard = [...history[stepNumber]]; const winner = calculateWinner(currentBoard); const moves = history.map((step, move) => { const description = move ? ' Go to move #' + move : ' Go to game start'; return ( <li key={move}> <button onClick={() => jumpTo(move)} > {description} </button> </li> ); }) let status; if (winner) { status = winner + " WON !!!!"; } else { status = 'Next player: ' + (xIsNext ? "X" : "O"); } return ( <div className="game"> <div className="game-board"> <Board squares = {currentBoard} handleClick={handleClick} /> </div> <div className="game-info"> <div className="status">{status}</div> <ol>{moves}</ol> </div> </div> ) }
about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

Los estados no se actualizan inmediatamente en los ganchos de reacción.

ex:

 const [counter, setCounter]=useState(0); handleClick(){ //counter = 0 setCounter(counter + 1); console.log(counter); //counter is old state so it is still 0 }

para su pregunta: ( history reemplaza hist )

 function handleClick(i) { const hist = history.slice(0, stepNumber+1); const currentBoard = [...history[stepNumber]]; const winner = calculateWinner(currentBoard); if (winner || currentBoard[i]) { setHistory(hist); return; }; currentBoard[i] = xIsNext ? "X" : "O"; setHistory(hist.concat([currentBoard])); setStepNumber (stepNumber + 1) setXIsNext(!xIsNext); }
about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda