English 中文(简体)
反应行为方式怪异
原标题:React behaves in a bizarre way

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 等同于真实 。

问题回答

您不应该在另一个状态变量的更新函数中更新变量状态。 使用 < code> useEffect hook 来执行将另一个变量添加为依赖性的任务 。

function whenClicked(index, value) {
        setSelection((prevSelection) => {
            const newSelection = [...prevSelection, { index, value }];

            // do not update any other state here
            return newSelection;
        })
    }

useEffect(()=>{
   if (selection.length === 2) {
                setAttempts((prevAttempts) => (prevAttempts + 1));
                setIseEnabled(false);
                sortCoupledElements(newSelection);
                setTimeout(() => {
                    setSelection([]);
                    setIseEnabled(true);
                }, 1000);
            }
}, [selection.length])




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签