I m trying to make this memory card game. It works fine but the attempts counter at the bottom behvaes in a bizarre way. In facts it sometimes increases by 1, some other times by 2. why does that happen?
import { useState } from react ;
import Button from "./Button";
const possibleElements = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8];
function randomNumber() {
const randIndex = Math.floor(Math.random() * possibleElements.length);
const randomNumber = possibleElements[randIndex];
possibleElements.splice(randIndex, 1);
return randomNumber;
}
const gameTable = [
[randomNumber(), randomNumber(), randomNumber(), randomNumber()],
[randomNumber(), randomNumber(), randomNumber(), randomNumber()],
[randomNumber(), randomNumber(), randomNumber(), randomNumber()],
[randomNumber(), randomNumber(), randomNumber(), randomNumber()]
];
export default function GameBoard() {
const [selection, setSelection] = useState([]);
const [coupledElements, setCoupledElements] = useState([]);
const [isEnabled, setIseEnabled] = useState(true);
const [attempts, setAttempts] = useState(0);
function sortCoupledElements(selection) {
if (selection[0].value === selection[1].value) {
setCoupledElements((prevCoupledElements) => {
const newCoupledElements = [...prevCoupledElements, selection[0].index, selection[1].index];
return newCoupledElements;
})
}
}
function whenClicked(index, value) {
setSelection((prevSelection) => {
const newSelection = [...prevSelection, { index, value }];
if (newSelection.length === 2) {
setAttempts((prevAttempts) => (prevAttempts + 1));
setIseEnabled(false);
sortCoupledElements(newSelection);
setTimeout(() => {
setSelection([]);
setIseEnabled(true);
}, 1000);
}
return newSelection;
})
}
return (
<main>
<div className="game-board">
<ol className="row">
{gameTable.map((row, rowIndex) => (
<li key={rowIndex}>
<ol className="column">
{row.map((value, colIndex) => {
const elementIndex = rowIndex * 4 + colIndex
return (
<li key={colIndex}>
<Button
isSelected={selection.some((element) => (element.index === elementIndex))}
ifClicked={whenClicked}
isCoupled={coupledElements.includes(elementIndex)}
isEnabled={isEnabled}
index={elementIndex}
value={value} />
</li>
)
})}
</ol>
</li>
))}
</ol>
</div>
<div id="attempts">
<h3>{attempts} attempts!</h3>
</div>
</main>
)
}
提前感谢您!
I thought it might be cause by the fact setAttempts rerender the component inside setSelection rerender. The problem is that it must be called when selection.length is 2. I tried to do it with a function:
function increaseAttempts() {
setAttempts((prevAttempts) => (prevAttempts +1))
}
并在 if ( newStection. laternal #%2)
语句之后的设定选择调用中调用此函数,但在此情况下,又发生了另外一件奇特的事情,即没有按钮保留其 是 sected
prop 等同于真实 。