【问题标题】:React setStates only updates state once and resets itReact setStates 只更新一次状态并重置它
【发布时间】:2022-01-23 15:58:42
【问题描述】:

你好,我对 React 有点陌生 我正在尝试制作一个有点像蛇的游戏,但我在运动中挣扎。

x 和 y 值从未真正改变过,他只能移动一个类似 1 个网格单元,但是当我按下另一个键时,他会转到起始位置并朝另一个方向移动 1 个单元格。我错过了什么?

function App() {

    const [_x, setX] = useState(0);
    const [_y, setY] = useState(0);

    let lastPressedKey = '';
    let gameTicker = null;


    function triggerMovement(x, y) {
        if (lastPressedKey === 100)
            move(10, 0);

        if (lastPressedKey === 97)
            move(-10, 0);

        if (lastPressedKey === 119)
            move(0, 10);

        if (lastPressedKey === 155)
            move(0, -10);
    }

    function move(x, y){
        console.log(lastPressedKey);
        console.log(x, _x, y, _y);
        setX(_x + x);
        setY(_y + y);
    }

    function handleKeyEvent(event) {
        lastPressedKey = event.keyCode;
    }

    function startTimer() {
        gameTicker = setInterval(triggerMovement, 1000);
    }

    function clearTimer() {
        clearInterval(gameTicker)
    }

    const element = (
        <div>
            <Screen farbe="darkslategray">
                <Snake x={_x} y={_y} farbe="red"/>
            </Screen>
            <button onClick={startTimer} style={{
                bottom: 5,
                position: 'absolute'
            }}>
                Start Game
            </button>
            <button onClick={clearTimer} style={{
                bottom: 5,
                left: 625,
                position: 'absolute'
            }}>
                StopGame
            </button>
        </div>
    )

    window.addEventListener('keypress', handleKeyEvent, true);

    return element;
}

function Snake(props){

    const [x, setX] = useState(250);
    const [y, setY] = useState(250);
    let speed = props.speed;

    const element = (
        <div style={{
            width: 10,
            height: 10,
            backgroundColor: props.farbe,
            position: 'absolute',
            left: props.x,
            bottom: props.y
        }}>

        </div>
    )
    return element;
}

我真的很想在这件事后面,但我从今天早上开始就想让这条蛇移动,我想知道我在这里错过了什么。

控制台日志总是

10, 0 , 0 , 0
10, 0 , 0 , 10
10, 0 , 0 , 0 ... 

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    这是因为陈旧的闭包

    这里

    function move(x, y){
        console.log(lastPressedKey);
        console.log(x, _x, y, _y);
        setX(_x + x);
        setY(_y + y);
    }
    

    _x_y 引用来自您调用 startTimer 函数的渲染的值。

    你可以使用setState的函数形式来避免这个问题:

    setX(ps => ps+x)
    

    【讨论】:

    • 正是我想要的……谢谢!有这么多“不同”的文档反应它很难阅读..
    猜你喜欢
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多