Ins*_*nno 4 reactjs react-hooks
我正在尝试在 React 中重新创建一个旧的 Flash 游戏。游戏的目标是按下按钮一段时间。
这是旧游戏:http : //www.zefrank.com/everysecond/index.html
这是我的新 React 实现:https : //codesandbox.io/s/github/inspectordanno/every_second
我遇到了问题。当释放鼠标时,我使用 Moment.js 时间库计算按下按钮和释放按钮之间的时间量。如果timeDifference之间onMouseDown和onMouseUp事件中targetTime,我希望游戏level,增加和targetTime提高为好。
我正在handleMouseUp事件处理程序中实现这个逻辑。我正在将预期时间打印到屏幕上,但逻辑不起作用。此外,当我console.log()时代时,它们与打印到屏幕上的不同。我相当确定timeHeld并且timeDifference没有正确更新。
最初我认为我做事件处理程序的方式有问题,我需要使用useRef()or useCallback(),但在浏览了其他一些问题后,我不太了解这些问题,无法知道在这种情况下是否必须使用它们。由于我不需要访问以前的状态,所以我认为我不需要使用它们,对吗?
游戏逻辑在这个包装组件中:
import React, { useState } from 'react';
import moment from 'moment';
import Button from './Button';
import Level from './Level';
import TargetTime from './TargetTime';
import TimeIndicator from './TimeIndicator';
import Tries from './Tries';
const TimerApp = () => {
const [level, setLevel] = useState(1);
const [targetTime, setTargetTime] = useState(.2);
const [isPressed, setIsPressed] = useState(false);
const [whenPressed, setPressed] = useState(moment());
const [whenReleased, setReleased] = useState(moment());
const [tries, setTries] = useState(3);
const [gameStarted, setGameStarted] = useState(false);
const [gameOver, setGameOver] = useState(false);
const timeHeld = whenReleased.diff(whenPressed) / 1000;
let timeDifference = Math.abs(targetTime - timeHeld);
timeDifference = Math.round(1000 * timeDifference) / 1000; //rounded
const handleMouseDown = () => {
!gameStarted && setGameStarted(true); //initialize game on the first click
setIsPressed(true);
setPressed(moment());
};
const handleMouseUp = () => {
setIsPressed(false);
setReleased(moment());
console.log(timeHeld);
console.log(timeDifference);
if (timeDifference <= .1) {
setLevel(level + 1);
setTargetTime(targetTime + .2);
} else if (timeDifference > .1 && tries >= 1) {
setTries(tries - 1);
}
if (tries === 1) {
setGameOver(true);
}
};
return (
<div>
<Level level={level}/>
<TargetTime targetTime={targetTime} />
<Button handleMouseDown={handleMouseDown} handleMouseUp={handleMouseUp} isGameOver={gameOver} />
<TimeIndicator timeHeld={timeHeld} timeDifference={timeDifference} isPressed={isPressed} gameStarted={gameStarted} />
<Tries tries={tries} />
{gameOver && <h1>Game Over!</h1>}
</div>
)
}
export default TimerApp;
Run Code Online (Sandbox Code Playgroud)
如果您想检查整个应用程序,请参阅沙箱。
如果您更新函数内的某些状态,然后尝试在同一函数中使用该状态,则不会使用更新后的值。函数会在调用函数时对状态值进行快照,并在整个函数中使用该值。这不是类组件中的情况this.setState,但钩子中的情况就是这样。this.setState也不会急切地更新值,但它可以根据一些事情在同一函数中更新(我没有足够的资格来解释)。
要使用更新的值,您需要一个引用。因此使用useRef钩子。[文档]
我已经修复了你的代码,你可以在这里看到它:https : //codesandbox.io/s/everysecond-4uqvv?fontsize=14
它可以用更好的方式编写,但你必须自己做。
在回答中添加代码以完成(有一些注释来解释内容,并提出改进建议):
import React, { useRef, useState } from "react";
import moment from "moment";
import Button from "./Button";
import Level from "./Level";
import TargetTime from "./TargetTime";
import TimeIndicator from "./TimeIndicator";
import Tries from "./Tries";
const TimerApp = () => {
const [level, setLevel] = useState(1);
const [targetTime, setTargetTime] = useState(0.2);
const [isPressed, setIsPressed] = useState(false);
const whenPressed = useRef(moment());
const whenReleased = useRef(moment());
const [tries, setTries] = useState(3);
const [gameStarted, setGameStarted] = useState(false);
const [gameOver, setGameOver] = useState(false);
const timeHeld = useRef(null); // make it a ref instead of just a variable
const timeDifference = useRef(null); // make it a ref instead of just a variable
const handleMouseDown = () => {
!gameStarted && setGameStarted(true); //initialize game on the first click
setIsPressed(true);
whenPressed.current = moment();
};
const handleMouseUp = () => {
setIsPressed(false);
whenReleased.current = moment();
timeHeld.current = whenReleased.current.diff(whenPressed.current) / 1000;
timeDifference.current = Math.abs(targetTime - timeHeld.current);
timeDifference.current = Math.round(1000 * timeDifference.current) / 1000; //rounded
console.log(timeHeld.current);
console.log(timeDifference.current);
if (timeDifference.current <= 0.1) {
setLevel(level + 1);
setTargetTime(targetTime + 0.2);
} else if (timeDifference.current > 0.1 && tries >= 1) {
setTries(tries - 1);
// consider using ref for tries as well to get rid of this weird tries === 1 and use tries.current === 0
if (tries === 1) {
setGameOver(true);
}
}
};
return (
<div>
<Level level={level} />
<TargetTime targetTime={targetTime} />
<Button
handleMouseDown={handleMouseDown}
handleMouseUp={handleMouseUp}
isGameOver={gameOver}
/>
<TimeIndicator
timeHeld={timeHeld.current}
timeDifference={timeDifference.current}
isPressed={isPressed}
gameStarted={gameStarted}
/>
<Tries tries={tries} />
{gameOver && <h1>Game Over!</h1>}
</div>
);
};
export default TimerApp;
Run Code Online (Sandbox Code Playgroud)
PS:不要使用不必要的第三方库,尤其是像 MomentJs 这样的大库。它们会显着增加您的捆绑包大小。使用可以使用 vanilla js 轻松获取当前时间戳。Date.now()将为您提供当前的 unix 时间戳,您可以减去两个时间戳以获得以毫秒为单位的持续时间。
你也有一些不必要的状态,比如gameOver,你可以检查if tries > 0来决定gameOver。
同样,targetTime您可以只使用level * .2,而无需额外的状态。
也whenReleased并不需要是一个引用或状态,它可以只是mouseUp处理局部变量。
状态更新器可以采用指示新状态的值,或者将当前状态映射到新状态的函数。当你的状态依赖于自身的突变时,后者是完成这项工作的正确工具。
如果您更新代码中使用该模式的位置,这应该有效
[value, setValue ] = useState(initial);
...
setValue(value + change);
Run Code Online (Sandbox Code Playgroud)
到
[value, setValue ] = useState(initial);
...
setValue((curValue) => curValue + change);
Run Code Online (Sandbox Code Playgroud)
例如,
if (timeDifference <= .1) {
setLevel((curLevel) => curLevel + 1);
setTargetTime((curTarget) => curTarget + .2);
} else if (timeDifference > .1 && tries >= 1) {
setTries((curTries) => {
const newTries = curTries - 1;
if (newTries === 1) {
setGameOver(true);
}
return newTries;
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5237 次 |
| 最近记录: |