You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React井字棋清除棋盘功能无效的问题求助

井字棋清除按钮无效的原因及修复方案

问题根源

  • 你在clear函数里直接给currentSquares赋值,但currentSquares只是从history状态派生的局部变量,不是React的状态本身。这种直接修改变量的操作不会触发组件重渲染,界面自然不会更新。
  • 清除逻辑没有更新history和currentMove这两个核心状态,组件依然沿用原来的状态数据渲染,所以棋盘没变化。

修复方案

修改Game组件里的clear函数,通过React的状态更新函数来重置状态:

function clear() {
  // 重置历史记录为初始空棋盘
  setHistory([Array(9).fill(null)]);
  // 把当前步数设回初始的0
  setCurrentMove(0);
}

修复逻辑说明

  • 用setHistory更新历史记录状态,让React感知到状态变化,触发组件重渲染。
  • 重置currentMove为0,确保currentSquares能正确获取到重置后的空棋盘数据。

修改后的完整Game组件代码

export default function Game() {
  const [currentMove, setCurrentMove] = useState(0);
  const [history, setHistory] = useState([Array(9).fill(null)]);
  let currentSquares = history[currentMove];

  function handlePlay(nextSquares) {
      const nextHistory = [...history.slice(0, currentMove + 1), nextSquares];
      setHistory(nextHistory);
      setCurrentMove(nextHistory.length - 1);
  }

  function clear() {
    setHistory([Array(9).fill(null)]);
    setCurrentMove(0);
  }

  return (
    <div className="game">
      <div className="game-board">
        <Board squares={currentSquares} onPlay={handlePlay} />
      </div>
      <div className="game-info">
        <button onClick={clear}>CLEAR</button>
      </div>
    </div>
  );
}

内容的提问来源于stack exchange,提问作者JobHunter69

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 08:50:01