我正在使用 OOP atm 构建一个国际象棋应用程序,它构建在 Next.JS 框架中。我已经在应用程序中进行了一些重构,现在它不会在状态改变时重新渲染屏幕上的对象。如果我通过移动 console.log 使服务器重新编译,它会突然呈现正确的东西,但是任何时候我想要在屏幕上重新呈现任何内容/更新我现在都必须这样做。我改变的主要是下面的电路板组件,我做错了什么吗?关于我可能做错了什么的任何想法?
import createSquares from '../functions/createSquares';
import calculateCheck from '../functions/calculateCheck';
import calculatePossibleMoves from '../functions/calculatePossibleMoves';
export default class ChessBoard {
constructor() {
this.arrayOfSquares = createSquares();
this.squareSelected = undefined;
this.playerTurn = 'White';
this.playerInCheck = false;
this.potentialMoves = calculatePossibleMoves(this);
}
selectSquare(square) {
this.squareSelected = square;
this.potentialMoves = square.chessPieceContained.legalMoves;
}
movePiece() {
this.playerTurn = this.playerTurn === 'White' ? 'Black' : 'White';
this.squareSelected = undefined;
this.potentialMoves = calculatePossibleMoves(this);
this.playerInCheck = calculateCheck(this);
}
}
** 编辑 **
渲染正在这个组件中进行:
export default function Board({ board }) {
return (
<div
style={{
display: 'flex',
position: 'relative',
flexWrap: 'wrap',
height: '41vh',
width: '41vh',
border: '0.5vh solid black',
}}>
{board.arrayOfSquares.map((square) => {
let p = square.chessPieceContained;
let color = square.black ? 'brown' : 'cream';
return (
<div
key={`${square.gridValue[0]}${square.gridValue[1]} `}
onClick={() => {
square.readyPiece(board);
}}
style={{
height: '5vh',
width: '5vh',
position: 'relative',
border: '0.1vh solid black',
backgroundColor: color,
}}>
{p ? (
<div className={p.selected ? 'highlight' : null}>
<p.image />
</div>
) : null}
</div>
);
})}
{board.potentialMoves
? board.potentialMoves.map((coordinate) => {
let top = coordinate[1] * 5 + 0.1;
let left = coordinate[0] * 5 + 0.1;
return (
<div
key={`${top} ${left}`}
onClick={() => {
let square = board.arrayOfSquares
.filter(
(tile) =>
tile.gridValue[0] === coordinate[0] &&
tile.gridValue[1] === coordinate[1]
)
.pop();
if (
square.gridValue !== board.squareSelected.gridValue &&
board.squareSelected !== undefined
) {
square.movePiece(board);
}
board.arrayOfSquares.forEach((square) => {
if (square.highlighted) {
square.setHighlight();
}
});
}}
style={{
position: 'absolute',
top: `${top}vh`,
left: `${left}vh`,
height: '4.8vh',
width: '4.8vh',
opacity: '0.5',
borderRadius: '50%',
backgroundColor: 'yellow',
}}></div>
);
})
: null}
</div>
);
}