setState 延迟一个状态

setState is delayed by one state

不知道我这里做错了什么,也许是菜鸟的错误。

我正在尝试重新创建国际象棋。

我的状态延迟了一个.. 即当我点击正方形显示棋子可能的走法时,可能的走法会出现,但只有在我第二次点击后,它们才会显示在正确的位置。对于第 3 次单击,第 2 次单击的状态将出现在正确的位置,依此类推。 我在这里做错了什么? 我从我的 next.js 应用程序

发送了一些代码示例

这是我的方形组件

export default function Square({
  x,
  y,
  color,
  content,
  contentClr,
  handleClick,
}) {
  const col = color == 'light' ? '#F3D9DC' : '#744253';

  return (
    <div
      className='square'
      x={x}
      y={y}
      style={{ backgroundColor: col }}
      onClick={() => handleClick(x, y)}
    >
      {content != '' && (
        <h1 style={{ color: contentClr == 'light' ? 'white' : 'black' }}>
          {content}
        </h1>
      )}
    </div>
  );
}

这是我的组件

import { useState, useEffect } from 'react';
import Square from './square';

import styles from '../styles/Board.module.css';
import rookMoves from './possibleMoves/rookMoves';

export default function Board({ initialBoard, lightTurn, toggleTurn }) {
  let size = 8;
  const [board, setBoard] = useState(initialBoard);
  const [possibleMoves, setPossibleMoves] = useState([]);
  //possibleMoves .. each possible move is represented as x, y coordinates.

  useEffect(() => {
    console.log('board state changed');
  }, [board]);

  useEffect(() => {
    console.log('possible moves state changed');
    console.log(possibleMoves);
    renderPossibleMoves();
  }, [possibleMoves]);

  const playerClickOnPiece = (x, y) => {
    let pos = getPossibleMoves(x, y, rookMoves, [left, right, up, down]);
    setPossibleMoves(pos);
  };

  //where to is object that has functions for directions in it
  const getPossibleMoves = (x, y, movePiece, whereTo) => {
    let posMoves = [];
    for (let i = 0; i < whereTo.length; i++) {
      posMoves = posMoves.concat(movePiece(board, x, y, whereTo[i]));
    }

    console.log(posMoves);
    return posMoves;
  };

  const renderPossibleMoves = () => {
    console.log('board from renderPossibleMoves ', board);
    let newBoard = board;
    for (let i = 0; i < possibleMoves.length; i++) {
      newBoard[possibleMoves[i].y][possibleMoves[i].x] = 10;
    }
    setBoard(newBoard);
  };

  const squareColor = (x, y) => {
    return (x % 2 == 0 && y % 2 == 0) || (x % 2 == 1 && y % 2 == 1)
      ? 'light'
      : 'dark';
  };

  const handleClick = (x, y) => {
    if (lightTurn && board[y][x] > 0) {
      console.log(
        `show me possible moves of light ${board[y][x]} on ${x} ${y}`
      );
      playerClickOnPiece(x, y);
    } else if (!lightTurn && board[y][x] < 0) {
      console.log(`show me possible moves of dark ${board[y][x]} on ${x} ${y}`);
      playerClickOnPiece(x, y);
    } else if (board[y][x] == 'Pm') {
      playerMove();
    }
  };

  return (
    <>
      <div className='board'>
        {board.map((row, y) => {
          return (
            <div className='row' key={y}>
              {row.map((square, x) => {
                return (
                  <Square
                    x={x}
                    y={y}
                    key={x}
                    color={squareColor(x, y)}
                    content={square}
                    contentClr={square > 0 ? 'light' : 'dark'}
                    handleClick={handleClick}
                    playerMove={toggleTurn}
                  />
                );
              })}
            </div>
          );
        })}
      </div>
    </>
  );
}

import { useState } from 'react';
import Board from './board';

let initialBoard = [
  [-4, -3, -2, -5, -6, -2, -3, -4],
  [-1, -1, -1, -1, -1, -1, -1, -1],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [1, 1, 1, 1, 1, 1, 1, 1],
  [4, 3, 2, 5, 6, 2, 3, 4],
];

export default function Game() {
  const [lightTurn, setLightTurn] = useState(true);

  const toggleTurn = () => {
    setLightTurn(!lightTurn);
  };

  return (
    <Board
      initialBoard={initialBoard}
      lightTurn={lightTurn}
      toggleTurn={toggleTurn}
    />
  );
}

我发送的示例仅显示了车的可能移动,但如果您单击任何灯片。

@juliomalves的评论有帮助! 我直接在 renderPossibleMoves 中改变状态。传播运算符解决了这个问题。

来自

let newBoard = board;

let newBoard = [...board];