谁能告诉我为什么这个setinterval越来越短

时间:2019-08-27 09:37:03

标签: reactjs

此setinterval会按预期触发,直到到达数组中的最后一个字符串并且不确定原因

    useEffect(() => {
        setwho(headerPhrases[
                Math.floor(Math.random() * headerPhrases.length)
                ])
        console.log('Change')
        }, [count])

        setInterval(() => {
            setcount(count + 1)

        }, 5000);

每次运行时它的启动速度越来越快,我在另一个应用程序中使用了相同的逻辑,并且可以正常工作。

1 个答案:

答案 0 :(得分:0)

在间隔的实现中,当组件重新渲染时,在每个渲染上都会创建一个新间隔。将时间间隔实现为一个钩子,如下所示:

const {
  useState,
  useEffect,
  useRef
} = React;

// Hook implementation for using setInterval()
function useInterval(callback, delay) {
  const savedCallback = useRef();

  // Remember the latest callback.
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  // Set up the interval.
  useEffect(() => {
    function tick() {
      savedCallback.current();
    }
    if (delay !== null) {
      let id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
}

// You may use hook `useInterval()` like: 
function Counter() {
  let [count, setCount] = useState(0);

  useInterval(() => {
    // Your custom logic here
    setCount(count + 1);
  }, 1000);

  return <h1 > Interval counter: {
    count
  } < /h1>;
}

ReactDOM.render(
  <Counter title="Example using Hooks:" />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>