我正在使用 State Hook 根据键盘命令(W、A、S、D)更新机器人的油门设置。我有一个 maxThrottle 状态变量来确保机器人不会跑得太快。但是,我使用滑块来调整 maxThrottle 命令。当您按下 W 键(前进)时,您应该获得分配给油门命令变量的当前 maxThrottle['forward'] 值。但是,每次 handleKey 函数运行时,我都会将 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} 分配给油门命令。
在 handleKey 函数中使用状态变量有什么问题吗?为什么我总是得到分配给throttleCommand 的maxThrottle 的初始值?
答案 0 :(得分:0)
迈克尔鲍尔!感谢您的修复。你是 100% 正确的。代码现在可以工作了。这是变化:
不正确的按键监听器:
useEffect(() => {
document.addEventListener('keydown',handleKey);
}, []);
解决/正确的按键监听器
useEffect(() => {
document.addEventListener('keydown', (e) => {
handleKey(e);
});
}, []);
经验教训 - 在 useEffect 内部使用箭头函数,以便回调函数更新!