(NextJS / ReactJS)“警告:文本内容不匹配。服务器:''客户端:'X'”导致奇怪的行为

时间:2021-07-26 23:36:10

标签: javascript reactjs typescript next.js

背景

我刚刚开始使用 Next.JS,到目前为止还没有遇到任何问题。然而,在让这个项目尝试更熟悉 Next.JS 的同时,我在控制台中遇到了这个警告(见下文):

Warning within console

此外,我认为这是在呈现我的“板”或一组按钮时出现意外行为的罪魁祸首。

Picture of board / group of buttons with repeating X's

很可能是我在我的代码中遗漏了一些东西(因为我对 ReactJS 和 NextJS 都比较陌生,但我不相信这是这种情况,因为在这个项目的早期版本中,正在渲染的单元格(按钮)与我用来表示这些单元格的二维数组不匹配。

Board.tsx

// Components
import BoardProps from "../interfaces/boardProps";
import { useState } from "react";
import Cell from "./cell";

// Constants and Globals
const emptyCell = ' ';
const mineCell = 'X';

export default function Board({ numberOfCells }: BoardProps) {
    const [cells, setCells] = useState(createBoard(numberOfCells));
    const numberOfCellsInRowAndColumn = Math.sqrt(numberOfCells); // TODO: validate
    const renderableBoard = getRenderableBoard(cells, numberOfCellsInRowAndColumn);

    return (
        <div>
            {renderableBoard}
        </div>
    );
}

function createBoard(numberOfCells: number) {
    let board = Array(numberOfCells).fill(emptyCell);
    board = generateMines(board);

    return board;
}

function getRenderableBoard(cells: any[], numberOfCellsInRowAndColumn: number) {
    let renderableBoard = [];

    for (let row = 0; row < numberOfCellsInRowAndColumn; row++) {
        let renderableRow = [];

        for (let column = 0; column < numberOfCellsInRowAndColumn; column++) {
            renderableRow.push(<Cell key={column} value={cells[column]}/>);
        }

        renderableBoard.push(<div key={row}>{renderableRow}</div>);
    }

    return renderableBoard;
}

function generateMines(cells: any[]) {
    const percentageOfMines = 0.15;
    const numberOfCells = cells.length;
    const numberOfMines = Math.floor(numberOfCells * percentageOfMines);
    let copyOfCells = cells.slice();
    
    for (let index = 0; index < numberOfMines; index++) {
        let randomIndex = Math.floor(Math.random() * numberOfMines);

        // Generates a random index until there are no duplicates
        while (copyOfCells[randomIndex] === mineCell) {
            randomIndex = Math.floor(Math.random() * numberOfCells);
        }

        copyOfCells[randomIndex] = mineCell;
    }

    return copyOfCells;
}

Cell.tsx

// Components
import CellProps from "../interfaces/cellProps";

export default function Cell({ value }: CellProps) {
    return (
        <button>
            {value}
        </button>
    );
}

如果有人能告诉我为什么我会收到此错误或任何见解,我们将不胜感激。

0 个答案:

没有答案