在当前情况下,我正在尝试检查最新索引(数字5)是否跳至1。因为我建立了一个功能计数器,当它达到最新索引时会自动跳至1,但是我也想拥有一个检查它何时从最新索引跳到第一个索引...此问题不一定需要反应钩。...
const App = ({ scoreCounter }) => {
const boolean = useRef(null);
const [ checkCounter, setCheckCounter ] = useState(false);
useEffect(() => {
const storedCounter = currentCounter;
boolean.current = storedCounter;
return () => storedCounter;
}, []);
useEffect(() => {
if(currentCounter == 5) {
}
console.log(boolean.current, currentCounter);
}, [boolean.current, currentCounter])
}
const mapStateToProps = state => {
return {
currentCounter: state.game.counter
}
}
答案 0 :(得分:0)
如果您使用的是类组件,则可以在prevState
函数中将state
与当前的componentDidUpdate
进行比较。在挂钩中,您可以实现与以下示例类似的内容:usePrevious。
使用链接中的usePrevious函数,您可以这样做:
const prevCount = usePrevious(checkCounter);
// Hook
function usePrevious(value) {
// The ref object is a generic container whose current property is mutable ...
// ... and can hold any value, similar to an instance property on a class
const ref = useRef();
// Store current value in ref
useEffect(() => {
ref.current = value;
}, [value]); // Only re-run if value changes
// Return previous value (happens before update in useEffect above)
return ref.current;
}
useEffect(() => {
if (prevCount === 5 && checkCounter === 1) {
// your code here
}
}, [prevCount, checkCounter])