Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

How to trigger a hook by pressing a button in React Native?

I'm making an app using React Native and facing a problem while making a countdown timer.

I needed to use setInterval in order to implement this, but I found that setInterval will not act what I have expected.

So I used custom Hooks from this post, and here's the code:

import React, { useState, useEffect, useRef } from 'react';

function useInterval(callback, delay) {
  const savedCallback = useRef();

  // Remember the latest callback.
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  // Set up the interval.
  useEffect(() => {
    function tick() {
      savedCallback.current();
    }
    if (delay !== null) {
      let id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
}

After that, I made a button to make a timer to be triggered:

const [leftTime, setTime] = useState(300000);
const triggerTimer = () => {
  useInterval(() => setTime(leftTime - 1), 1000);
};

return (
  <>
    <Text>{leftTime}</Text>
    <TouchableOpacity onPress={() => triggerTimer()}
      <Text>Start Countdown!</Text>
    </TouchableOpacity>
  </>
);

However, I got an error saying 'Invalid hook call. Hooks can only be called inside of the body of a function component.'

I already know that Hooks must be called at the very top of the function component, but is there any way to trigger a hook by pressing a button in the app?

Also, I want to stop the timer automatically and do something after that when the state 'leftTime' becomes 0.

question from:https://stackoverflow.com/questions/65893926/how-to-trigger-a-hook-by-pressing-a-button-in-react-native

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...