首页 > 解决方案 > 在反应中有顶级变量是不是很糟糕?

问题描述

我正在学习反应,拥有顶级变量似乎是错误的。我总是听说我需要使用状态,但是当有很多类/函数时很难使用状态。例如,这是我的代码:

import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import { classNames } from "classnames";
import './index.css';
var [a1, b1, c1] = [];
var finished = false;

function Square(props) {
  return (
    <button className={finished ? (props.valid ? "squares" : "squarez") : 'square'} onClick={() => props.onClick()}>
      {props.value}
    </button>
  );
}

function Board() {

  const [arr, setArr] = useState(Array(9).fill(null));
  const [xIsNext, setXIsNext] = useState(true);
  function handleClick(i) {
    if (!arr[i] && !winner) {
      const squares = arr.slice();
      squares[i] = xIsNext ? 'X' : 'O';
      setArr(squares);
      setXIsNext(!xIsNext);
    }
  }

  function renderSquare(i) {
    return <Square value={arr[i]} onClick={() => handleClick(i)} valid={a1 === i || b1 === i || c1 === i ? true : false} />;
  }
  const winner = calculateWinner(arr);
  const status = winner ? 'Winner is: ' + winner : 'Next player: ' + (xIsNext ? 'X' : 'O');
  return (
    <div>
      <div className="status">{status}</div>
      <div className="board-row">
        {renderSquare(0)}
        {renderSquare(1)}
        {renderSquare(2)}
      </div>
      <div className="board-row">
        {renderSquare(3)}
        {renderSquare(4)}
        {renderSquare(5)}
      </div>
      <div className="board-row">
        {renderSquare(6)}
        {renderSquare(7)}
        {renderSquare(8)}
      </div>
    </div>
  );

}

class Game extends React.Component {
  render() {
    return (
      <div className="game">
        <div className="game-board">
          <Board />
        </div>
        <div className="game-info">
          <div><button onClick={Board}>alaa </button></div>
          <ol>{/* TODO */}</ol>
        </div>
      </div>
    );
  }
}
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]) {
      [a1, b1, c1] = lines[i];
      finished = true;
      return squares[a];
    }
  }
  return null;
}
// ========================================

ReactDOM.render(
  <Game />,
  document.getElementById('root')
);

来自 React 的官网教程。如您所见,我在顶部有 'finished' 和 'a1' 'b1' 'c1' 变量。如何在不使用顶级变量的情况下使用 square 类中的状态挂钩重写它们?作为参考,这是我正在制作的教程,但我玩了一下它来学习:https ://reactjs.org/tutorial/tutorial.html

标签: javascripthtmlreactjsweb

解决方案


推荐阅读