【问题标题】:Reactjs - How to add 1 item to array per second by using Hook useEffect and setIntervalReactjs - 如何通过使用 Hook useEffect 和 setInterval 每秒向数组添加 1 个项目
【发布时间】:2022-12-01 16:42:24
【问题描述】:
/**
   * init array: [1, 2]
   * Expect
   * array per 1s: [1, 2, 3]
   * array per 2s: [1, 2, 3, 4]
   * array per (n)s: [1, 2, 3, 4, ..., n]
   */
  const [countList, setCountList] = useState([]);
  const counter = useRef(0);
  useEffect(() => {
    const interval = setInterval(() => {
      counter.current = counter.current + 1;
      setCountList([...countList, counter.current]);
    }, 1000);
    return () => clearInterval(interval);
  });

  return (
    <>
      <div>{countList.map((count) => count + ',')}</div>
    </>
  );

我希望每一秒,数组推送 1 个项目,然后在 UI 上显示它,但数组只更新最后一个项目。 Exp [1, 2] => [1, 3] => [1, 4] ...

【问题讨论】:

标签: reactjs react-hooks setinterval


【解决方案1】:

尝试这个。

countList 更新后,您必须重新生成 interval

  const [countList, setCountList] = React.useState([]);
  const counter = React.useRef(0);

  React.useEffect(() => {
    const interval = setInterval(() => {
      counter.current = counter.current + 1;

      setCountList([...countList, counter.current]);
    }, 1000);

    return () => clearInterval(interval);
  }, [countList]);

【讨论】:

  • 谢谢,它对我有用。
【解决方案2】:

正确的做法是在挂载时只设置一次间隔,而不是反复设置和清除它。有点违背了设置间隔的目的。您需要使用回调函数来获取之前的值,并将一个空的依赖数组传递给 useEffect

  useEffect(() => {
    const interval = setInterval(() => {
      setCountList(prev => [...prev, counter.current++]);
    }, 1000);
    return () => clearInterval(interval);
  },[]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2020-07-24
    • 2021-04-26
    • 2021-12-22
    • 2021-07-04
    • 2015-09-13
    • 1970-01-01
    相关资源
    最近更新 更多