繁体   English   中英

更新反应 function 内部的 state 变量

[英]Updating a state variable inside of a react function

我正在使用 State 挂钩根据键盘命令(W、A、S、D)更新机器人的油门设置。 我有一个 maxThrottle state 变量,可确保机器人不会太快 go。 但是,我使用 slider 来调整 maxThrottle 命令。 当您按下 W 键(前进)时,您应该获得分配给 throttleCommand 变量的当前 maxThrottle['forward'] 值。 但是,每次运行 handleKey function 时,我只是将 throttleCommand['forward'] 设置为初始值 30,即使我已将 maxThrottle(使用 setMaxThrottle)更改为更高的数字,例如 80。

function App(){

//state hooks
    const [ throttleCommand, setThrottleCommand ] = useState({ forward: 0, turn: 0 });
    const [ maxThrottle, setMaxThrottle ] = useState({ forward: 30, turn: 15 });

useEffect(
        () => {
            sendThrottle(throttleCommand);
        },
        [ throttleCommand ]
    );

    const handleKey = (e) => {
        switch (e.code) {
            case 'KeyW':
                setThrottleCommand({ ...throttleCommand, forward: maxThrottle.forward });
                break;
            case 'KeyS':
                //THIS SHOULD TURN IT OFFF
                setThrottleCommand({ forward: 0, turn: 0 });
                break;
            case 'KeyA':
                //turn left
                setThrottleCommand({ ...throttleCommand, turn: -maxThrottle.turn });
                break;
            case 'KeyD':
                setThrottleCommand({ ...throttleCommand, turn: maxThrottle.turn });
                break;
            default:
                break;
        }
    };


    const sendThrottle = () => {
        //here I test the throttleCommand
        console.log('sending command', throttleCommand);
        axios.get(`/throttle/${throttleCommand.forward}/${throttleCommand.turn}`).then((res) =>    {
            setThrottleData(res.data);
        });
    };

....

}

我已验证我已成功将 maxThrottle 更新为 {forward:80,turn:20},但是当我按下 W 键时,throttleCommand 记录为 {forward:30, turn:0}。 我希望看到 {forward:80,turn:0} 分配给了 throttleCommand。

在 handleKey function 中使用 state 变量有什么问题吗? 为什么我总是将 maxThrottle 的初始值分配给 throttleCommand?

迈克尔鲍尔。 感谢您的修复。 你是 100% 正确的。 代码现在可以工作了:更改如下:

不正确的keydown监听器:

    useEffect(() => {
        document.addEventListener('keydown',handleKey);
    }, []);

已解决/正确的按键监听器

    useEffect(() => {
        document.addEventListener('keydown', (e) => {
            handleKey(e);
        });
    }, []);

经验教训 - 在 useEffect 中使用箭头函数,以便回调 function 更新!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM