反应不正确更新状态

时间:2020-04-22 13:20:35

标签: javascript reactjs react-hooks state use-effect

我正在使用jsx功能组件创建一个简单的机会骰子游戏,但是,当我单击创建滚动的按钮时,它将显示发布状态。这是我的组件代码(减少了不必要的代码),这对于编码来说是相当新的,因此如果有点粗糙,请原谅。另外,下面是发生这种情况的一个示例:https://gyazo.com/3f708e053a361e85e9b91d84b3e1849b

谢谢!

import React, { Fragment, useState } from "react";

...

const Dice = () => {


    // Declare state
    const [gameState, setState] = useState("roll");
    const [randomRoll, setRandom] = useState(13.37);
    const [rollSep, setRollSep] = useState([0, 0, 0, 0]);

    // Roll the dice animation
    const roll = () => {
        setState("Rolling...");


        setTimeout(() => {

            setRandom(Math.floor(Math.random() * 10000) / (1 * 100))
            setState("Rolled " + randomRoll);

        }, 500);
    };

    return (
        <Fragment>
            <Box>

                ...

                {animationState === "blitz" ? (
                    <StyledBlitz transform={`translateX(${randomRoll}%)`}>
                        <h2>{randomRoll}</h2>
                        <img src={dice} alt="dice" />
                    </StyledBlitz>
                ) : null}

                ...

                <Button
                    onClick={roll}
                >
                    {gameState}
                </Button>

            </Box>
        </Fragment>
    );
};

export default Dice;

0 个答案:

没有答案