添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

clearInterval不起作用(已经按照其他问题的步骤进行了处理)。

0 人关注

我知道这个问题相当普遍,我已经按照那里列出的解决方案,但没有成功,这就是为什么我提出了一个新问题。

我试图在React Native上创建一个时间/时钟(如果有人有一个库可以做到这一点,那也会很感激),目前是这样创建的。

  const [time, setTime] = useState(moment(new Date()).format('hh:mm A (DD/MM/YYYY)'));
  function TimeView() {
    setTime(moment(new Date()).format('hh:mm A (DD/MM/YYYY)'));
  const timeVar = setInterval(TimeView, 60000);

我试着用const、var、let来表示timeVar,但没有成功。

当用户移动到下一个屏幕时,让定时器关闭,就像这样。

  <Button
      onPress={{   
        // navigation code here
            clearInterval(timeVar);
 </Button>

我不知道我在这里做错了什么,希望得到任何帮助。谢谢!

Edit:根据Uğur Eren的建议,我定义了这个函数,但是定时器并没有通过这个方法工作。

function Interval(fn, time) {
  const timer = useRef();
  this.start = function () {
    if (!this.isRunning()) {
      timer.current = setInterval(fn, time);
  this.stop = function () {
    clearInterval(timer);
    timer.current = false;
  this.isRunning = function () {
    return timer !== false;
    
javascript
android
react-native
setinterval
clearinterval
Sankomil
Sankomil
发布于 2021-03-11
2 个回答
kkk
kkk
发布于 2021-03-11
0 人赞同

试试这个。你应该在组件安装时使用setInterval。

 const [time, setTime] = useState(moment(new Date()).format('hh:mm A (DD/MM/YYYY)'));
 const [timeVar, setTimeVar] = useState<any>();
 useEffect(() => {
  const interval = setInterval(() => {
    setTime(moment(new Date()).format('hh:mm A (DD/MM/YYYY)'));
  }, 60000);
  setTimeVar(interval);
 }, []);

对于按钮,你必须传递一个函数来清除timeVar。

<Button
      onPress={() => {   
        // navigation code here
            if(timeVar) {
              clearInterval(timeVar);
 </Button>
    
尝试了你的解决方案,但不幸的是没有成功。我在控制台记录了timevar,当我按下按钮时,它显示了一个不同的id。不知道那里发生了什么。
Sankomil
Sankomil
发布于 2021-03-11
已采纳
0 人赞同

如果你偶然来到这里寻找答案,我希望这个答案能帮助你(对我有用)。

首先创建了定时器useState变量,以及要运行的函数。

 const [time, setTime] = useState(moment(new Date()).format('hh:mm A (DD/MM/YYYY)'));
 function TimeView() {
    setTime(moment(new Date()).format('hh:mm A (DD/MM/YYYY)'));
 const timeVar = useRef();

接下来,设置一个useEffect钩子,在页面第一次加载时启动你的时间间隔。

  useEffect(() => {
    if (isFocused) {
      timeVar.current = setInterval(TimeView, 60000);
  }, []);