time travel

This commit is contained in:
djmil 2023-07-31 19:09:01 +02:00
parent e6a8ba41fd
commit cba59847bf

View File

@ -60,15 +60,20 @@ function Board({ xIsNext, squares, onPlay }) {
function App() { function App() {
const [xIsNext, setXIsNext] = useState(true); const [xIsNext, setXIsNext] = useState(true);
const [history, setHistory] = useState([Array(9).fill(null)]); const [history, setHistory] = useState([Array(9).fill(null)]);
const currentSquares = history[history.length - 1]; const [currentMove, setCurrentMove] = useState(0);
const currentSquares = history[currentMove];
function handlePlay(nextSquares) { function handlePlay(nextSquares) {
setHistory([...history, nextSquares]); const nextHistory = [...history.slice(0, currentMove + 1), nextSquares];
setHistory(nextHistory);
setCurrentMove(nextHistory.length - 1);
setXIsNext(!xIsNext); setXIsNext(!xIsNext);
} }
function jumpTo(nextMove) { function jumpTo(nextMove) {
// TODO setCurrentMove(nextMove);
setHistory(history.slice(0, nextMove+1));
setXIsNext(nextMove % 2 === 0);
} }
const moves = history.map((squares, move) => { const moves = history.map((squares, move) => {
@ -79,7 +84,7 @@ function App() {
description = 'Go to game start'; description = 'Go to game start';
} }
return ( return (
<li> <li key={move}>
<button onClick={() => jumpTo(move)}>{description}</button> <button onClick={() => jumpTo(move)}>{description}</button>
</li> </li>
); );