React hooks使用 setInterval
// 自定义 useInterval Hook import React, { useState, useEffect, useRef } from 'react'; export function useInterval(callback, delay) { const savedCallback = useRef(); // Remember the latest callback. useEffect(() => { savedCallback.current = callback; }); // Set up the interval. useEffect(() => { function tick() { savedCallback.current(); } if (delay !== null) { let id = setInterval(tick, delay); return () => clearInterval(id); } }, [delay]); }
使用:
import React, { useState, useEffect, useRef } from 'react'; function Counter() { let [count, setCount] = useState(0); useInterval(() => { // Your custom logic here setCount(count + 1); }, 1000); return <h1>{count}</h1>; }
摘自原文:https://segmentfault.com/a/1190000018224631