美文网首页
function hooks

function hooks

作者: 邹小邹大厨 | 来源:发表于2019-08-07 13:34 被阅读0次

setInterval 问题

import React, { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";

function Counter() {
  let [count, setCount] = useState(0);

  useEffect(() => {
    console.log(333);
    let id = setInterval(() => {
      console.log(222);
      setCount(count + 1);
    }, 1000);
    return () => {
      console.log(1111);
      clearInterval(id);
    };
  });

  return <h1>{count}</h1>;
}

const rootElement = document.getElementById("root");

// Second interval to demonstrate the issue.
// Fast updates from it cause the Counter's
// interval to constantly reset and never fire.
// setInterval(() => {
//   ReactDOM.render(<Counter />, rootElement);
// }, 100);
ReactDOM.render(<Counter />, rootElement);

运行结果是正常的,通过打印可以看出,它是先清除setInterval再添加setInterval来执行的,这样如果时间设置的较大没什么问题,但是如果设置时间比较小的话,还没有等到setInterval执行的时候,就已经被清除了

setInterval(() => {
  ReactDOM.render(<Counter />, rootElement);
}, 100);

可以看到一直没有得到执行就会被清除


image.png

这是因为每次render,都会执行useEffect,但是如果这样的代码的话

import React, { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    let id = setInterval(() => {
      setCount(count + 1);
    }, 1000);
    return () => {
      console.log(1234);
      clearInterval(id);
    };
  }, []);

  return <h1>{count}</h1>;
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Counter />, rootElement);

可以看到它会只执行一次,因为setCount只是取得了第一次传入的count,也就是0,所以数字就一直为1,但是循环还是在执行

image.png
可以参考如下链接进行使用setInterval
https://overreacted.io/making-setinterval-declarative-with-react-hooks/

相关文章

  • function hooks

    setInterval 问题 运行结果是正常的,通过打印可以看出,它是先清除setInterval再添加setIn...

  • 使用Hooks实现生命周期

    封装自定义 Hooks - 生命周期 hooks 在 function 组件中使用

  • 十四、react-hooks和react-dnd

    hooks 注意:hooks需要React v16.7.0-alpha以上才支持 只能放到function里面使用...

  • 谈谈React Hooks之useEffect

    自从Hooks出现,函数式组件(Function Component)的功能在不断丰富,你很可能已经运用Hooks...

  • Hooks实践总结

    Hooks在应用中的实践 如何定义个Function Component 处理状态 useState(推荐) us...

  • React Hooks

    Hooks 是 React 最近的一个提案,他解决在 Function component 上面使用 state。...

  • 9.hooks源码(想知道Function Component是

    人人都能读懂的react源码解析(大厂高薪必备) 9.hooks源码(想知道Function Component是...

  • React Hooks『React今年最劲爆的新特性』

    你还在为该使用无状态组件(Function)还是有状态组件(Class)而烦恼吗? ——拥有了hooks,你再也不...

  • React Hooks

    你还在为该使用无状态组件(Function)还是有状态组件(Class)而烦恼吗?——拥有了hooks,你再也不需...

  • 30分钟精通React Hooks

    你还在为该使用无状态组件(Function)还是有状态组件(Class)而烦恼吗?——拥有了hooks,你再也不需...

网友评论

      本文标题:function hooks

      本文链接:https://www.haomeiwen.com/subject/ctzskctx.html