React Hook检查计数器是否从5(最新索引)跳到1(第一索引)

时间:2019-11-12 22:38:34

标签: reactjs react-hooks

在当前情况下,我正在尝试检查最新索引(数字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 
    }
 }

1 个答案:

答案 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])