[React] 리액트 시작하기 (2)

Lynn·2021년 3월 27일
0

React

목록 보기
2/17
post-thumbnail

📌 게임 완성하기

State 끌어올리기

현재까지는 각각의 Square 컴포넌트에서 state를 유지하고 있었지만, 승자를 확인하기 위해 부모 Board 컴포넌트에서 게임의 상태를 한번에 저장하자. (공유 state)

class Board extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      squares: Array(9).fill(null),
    };
  }
  ...

Board에 생성자를 추가하고, 9개의 사각형에 해당하는 9개의 null 배열을 초기 state로 초기화한다.

Square에게 현재 값('X', 'O', null)을 표현하도록 renderSquare 함수를 수정하고, 위에 handleClick() 함수도 추가한다.

  ...
  handleClick(i) {
    const squares = this.state.squares.slice();
    squares[i] = 'X';
    this.setState({squares: squares});
  }

  renderSquare(i) {
    return (
      <Square
        value={this.state.squares[i]}
        onClick={() => this.handleClick(i)}
      />
    );
  }
  ...

Square는 이제 value prop, onClick prop을 받는다. 컴포넌트는 자신이 정의한 state에만 접근할 수 있으므로 Square에서 Board의 state를 직접 변경할 수 없다. 대신에 Board에서 Square로 함수를 전달(handleClick)하고. Square는 사각형을 클릭할 때 함수를 호출(onClick)할 것이다. 이에 따라 Square를 수정해주자.

class Square extends React.Component {
  render() {
    return (
      <button
        className="square"
        onClick={() => this.props.onClick()}
      >
        {this.props.value}
      </button>
    );
  }
}

이제 Square는 게임의 상태를 유지할 필요가 없기 때문에 constructor를 지워 줘야 한다.

위 코드까지 수정을 마치면, Square 컴포넌트는 Board에 의해 제어되는 컴포넌트가 된다.

불변성이 왜 중요할까요?

이전 코드에서 기존 배열을 수정하는 것이 아니라 .slice() 연산자를 사용해 squares 배열의 사본을 만들어 수정했다.

일반적으로 데이터를 변경하는 두 가지 방법에는
<데이터의 값 직접 변경>, <원하는 변경값을 가진 새로운 사본으로 데이터를 교체>가 있다.

둘의 결과는 동일하지만 교체 즉, 불변성을 사용하면 자습서 설명 참고와 같은 이점들을 얻을 수 있다. 리액트 시작하기(3)에서 추가 설명 예정

함수 컴포넌트

Square를 state 없이 render 함수만을 가지는 함수 컴포넌트로 변경한다. 클래스보다 간단하다는 점ㅁ!

function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}

순서 만들기

이제 'X' 차례에서 'O' 차례로 넘어가는 코드를 만들 차례다. Board의 생성자에서 xIsNext라는 boolean 값을 초기 state로 지정한다.

class Board extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      squares: Array(9).fill(null),
      xIsNext: true,
    };
  }
  ...

플레이어가 수를 둘 때마다 xIsNext 이 뒤집혀 다음 차례가 누군지 결정하고 게임의 state가 저장될 것이다. BoardhandleClick 함수에 xIsNext 를 뒤집는 코드를 setState() 내에 추가해 준다.

  ...
  handleClick(i) {
    const squares = this.state.squares.slice();
    squares[i] = this.state.xIsNext ? 'X' : 'O';
    this.setState({
      squares: squares,
      xIsNext: !this.state.xIsNext,
    });
  }
  ...

render 함수에도 다음 차례가 누구인지 보여주는 코드를 추가한다.

  render() {
    const status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');

    return (
      // 나머지는 그대로입니다.

승자 결정하기

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }
  return null;
}

위의 승자를 계산하는 코드를 파일 최하단에 추가하고, 누가 우승했는지 확인하기 위해 Boardrender 함수에서 calculateWinner(squares) 를 호출해 우승자를 보여준다.

  render() {
    const winner = calculateWinner(this.state.squares);
    let status;
    if (winner) { //우승자가 있으면
      status = 'Winner: ' + winner;
    } else {
      status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
    }

    return (
      // 나머지는 그대로입니다.

또, 게임이 끝났거나 칸이 이미 채워졌다면 BoardhandleClick 함수가 클릭을 무시하고 return 하도록 변경한다.

  handleClick(i) {
    const squares = this.state.squares.slice();
    if (calculateWinner(squares) || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? 'X' : 'O';
    this.setState({
      squares: squares,
      xIsNext: !this.state.xIsNext,
    });
  }

지금까지의 전체 코드 확인

틱택토 게임 완성 🙃 다음 글에서는 동작 되돌리기 기능 추가 예정

profile
wanderlust

0개의 댓글