React Hooks 实现一个计时器组件
阅读原文时间:2023年07月08日阅读:1

React Hooks 实现一个计时器组件

https://reactjs.org/docs/hooks-reference.html#useeffect

import React, { useState, useEffect } from "react";
import "./style.css";

const App = () => {
  const [count, setCount] = useState(0);
  useEffect(() => {
    const timer = setTimeout(() => {
      const counter = count + 1;
      setCount(counter);
    }, 1000);
    return () => clearTimeout(timer);
  }, [count]);
  // useEffect(() => {
  //   const timer = setTimeout(() => {
  //     const counter = count + 1;
  //     setCount(counter);
  //   }, 1000);
  //   return () => clearTimeout(timer);
  // }, []);
  // once bug
  // 观察值,如果是 [] 空数组,组件只会渲染一次,因为没有监听到任何值发生的变化
  return (
    <section>
      <div>count = {count}</div>
    </section>
  );
};

export default App;

Returns a memoized callback

const memoizedCallback = useCallback(
  () => {
    doSomething(a, b);
  },
  [a, b],// 观察值,如果是 [] 空数组,组件只会渲染一次,因为没有监听到任何值发生的变化
);

https://reactjs.org/docs/hooks-reference.html#usecallback

Returns a memoized value.

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

const memoizedValue = useMemo(() => {
  return  computeExpensiveValue(a, b);
},  [a, b]);

https://reactjs.org/docs/hooks-reference.html#usememo

optimize performance / 优化性能

useMemo and useCallback hooks usage guide to increasing the performance of our applications

https://stackblitz.com/edit/react-hooks-useeffect-timer?file=src%2FApp.js

https://stackblitz.com/edit/react-hooks-usememo-timer?file=src%2FApp.js



xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器