react hook useRef

原文链接: react hook useRef

上一篇: react hook useEffect

下一篇: react hook useMemo

可以暂停的定时器, 使用ref保存 定时器的handler

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

export default () => {
  const [count, setCount] = useState(0);
  const ref = useRef(null);

  const start = () => {
    console.log("start");
    if (!ref.current) {
      console.log("start ref");
      ref.current = getInterval();
    }
  };

  const getInterval = () => setInterval(() => setCount((c) => c + 1), 100);
  const stop = () => {
    console.log("stop", ref);
    if (ref.current) {
      console.log("clear");
      clearInterval(ref.current);
      ref.current = null;
    }
  };

  useEffect(() => {
    ref.current = getInterval();
    console.log("===", ref);
  }, []);
  return (
    <div>
      count: {count}
      <div>
        <button onClick={stop}>stop</button>
        <button onClick={start}>start</button>
      </div>
    </div>
  );
};

修改ref不会重新渲染, 页面数据不会变化, 但是 输出可以看到ref已经变了

up-68c8fef2fb66ad6e77c154a8329aed93630.png

import React, { useEffect, useRef } from "react";

export default (props) => {
  const ref = useRef(0);
  useEffect(() => {
    setInterval(() => {
      console.log(ref.current);
      ref.current++;
    },100);
  }, []);
  return <div>{ref.current}</div>;
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值