
const moves = history.map((squares, move) => { let description; let searched; let index; // searched를 찾았을 때의 index if (move > 0) { for (let i = 0; i < history[move].length; i++) { if (history[move][i] && history[move][i] !== history[move - 1][i]) { searched = `(${Math.floor(i / 3)},${i % 3})`; index = move; continue; } } if (currentMove === index) { //index와 현재 행동순서인 currentMove를 비교하여 처리 description = 'You are at move #…' + searched; } else { description = 'Go to move #' + searched; } } else { description = 'Go to game start'; } return ( <li key={move}> <button onClick={() => jumpTo(move)}>{description}</button> </li> ); });
Tic-Tac-Toe 튜토리얼 5가지 개선사항중 첫번째인 1.For the current move only, show “You are at move #…” instead of a button.
현재 가장 마지막 행동의 버튼에만 You are at move #…으로 변경하기이다.
return ( <div className="game"> <div className="game-board"> <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} /> </div> <div className="game-info"> <ol>{moves}</ol> </div> </div> );
moves 함수에서 index 변수를 추가하고, currentMove와 index를 비교하여 버튼에 들어갈 텍스트를 처리하는 방식으로 수정하였다.
searched를 object로 변경하거나 description,searched,index를 하나의 object로 통합하는 방법도 생각해보았는데, 기존 소스를 최대한 수정하지 않고 추가하는 방식으로 구현하려고 새로운 변수를 추가하였다.
리액트 근본 틱택토..! 좋은 글 잘 보고 갑니다 :)