井字游戏提前回归?

问题描述 投票:0回答:1

我对 React 还很陌生,正在尝试理解 Tic-tac-toe 中的代码。


import { useState } from "react";
//side function Square (will have value and onClick)
function Square({ value, onSquareClick }) {
  return (
    <button className="square" onClick={onSquareClick}>
      {value}
    </button>
  );
}

//function to find winner
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[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }
  return null;
} 


export default function Board() {
  //1st, set 9 array for squares
  const [squares, setSquares] = useState(Array(9).fill(null));
  const [xIsNext, setXIsNext] = useState(true);
  function handleClick(i) {
    if (winner || squares[i]) {
      return;
    }
    const nextSquares = squares.slice();
    if (xIsNext) {
      nextSquares[i] = "X";
    } else {
      nextSquares[i] = "O";
    }
    setXIsNext(!xIsNext);
    setSquares(nextSquares);
  }
  const winner = calculateWinner(squares);
  let status;
   if (winner) {
     status = "Winner is: " + winner;
   } else {
     status = "There is no winner";
   }

   return (
     <>
       <div className="status">{status}</div>
       <div className="board-row">
         <Square value={squares[0]} onSquareClick={() => handleClick(0)} />
         <Square value={squares[1]} onSquareClick={() => handleClick(1)} />
         <Square value={squares[2]} onSquareClick={() => handleClick(2)} />
       </div>

       <div className="board-row">
         <Square value={squares[3]} onSquareClick={() => handleClick(3)} />
         <Square value={squares[4]} onSquareClick={() => handleClick(4)} />
         <Square value={squares[5]} onSquareClick={() => handleClick(5)} />
       </div>

       <div className="board-row">
         <Square value={squares[6]} onSquareClick={() => handleClick(6)} />
         <Square value={squares[7]} onSquareClick={() => handleClick(7)} />
         <Square value={squares[8]} onSquareClick={() => handleClick(8)} />
      </div>
    </>
   );
  }

在 Board 函数中,handleClick 函数有以下部分: if (winner || squares[i]){return}.... 使函数在任一条件下都提前返回。如果存在获胜者,则将不再允许执行任何操作,或者如果您单击已填充的方块,您仍然可以继续前进并填充其他方块。

那么为什么这两种情况在使用相同的提前返回处理时会有不同的反应??? 希望这是有道理的。非常感谢大家!

reactjs tic-tac-toe
1个回答
0
投票

不同的是

winner
有一个不依赖于
i
的值:如果它是true,那么无论你点击哪里它都会是true。但
squares[i]
的值取决于
i
:对于
i
的一个值,它可能为真(即占用),而对于另一个值则可能为假(即自由)。

无论哪种方式,提前返回仅涉及正在处理的单击。

在游戏获胜的情况下,用户仍然可以单击多个方块,但很明显,在所有这些情况下,单击处理程序都会快速退出,因为在所有这些情况下

winner
都是 true。

© www.soinside.com 2019 - 2024. All rights reserved.