javascript 如何在React js中创建每秒添加新数据数组的计数器

icomxhvb  于 2022-12-17  发布在  Java
关注(0)|答案(3)|浏览(125)

所以我基本上是想让它不断地用计数器无限地添加新的数据数组,所以每一秒它都应该用下一个数字添加一个新的数组。

data={[
          { x: 1, y: 1 },
          { x: 2, y: 2 },
          { x: 3, y: 3 },
          { x: 4, y: 4 },
          { x: 5, y: 5 },
          { x: 6, y: 6 },
        ]}
xggvc2p6

xggvc2p61#

let data=[]
function add_element(){
data.push({x:data.length, y:data.length})

}

setInterval(add_element, 1000);

出于测试目的:

let data=[]
function add_element(){
data.push({x:data.length, y:data.length})
if(data.length==2) {
console.log(data)}
}

setInterval(add_element, 1000);
z5btuh9x

z5btuh9x2#

const [data, setData] = useState([]);

useEffect(() => {
    const timer = setTimeout(() => {
                    setData((prev) => [...prev, { x: prev.length, y: prev.length }]);
                  }, 1000);
  
    return () => clearTimeout(timer);
  }, [data]);

// For testing purposes you can log the result in the console by
// uncommeting the following line:
// console.log(data);
ohtdti5x

ohtdti5x3#

我喜欢React的贡献者之一Dan Abramov的这个定制useInterval钩子。

const React = window.React;
const ReactDOM = window.ReactDOM;

const { useState, useEffect, useRef } = React;

// @see https://overreacted.io/making-setinterval-declarative-with-react-hooks/
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]);
}

function App() {
  let [items, setItems] = useState([]);

  useInterval(() => {
    setItems((prevItems) => {
      const newSize = prevItems.length + 1;
      const newItesm = [...prevItems, { x: newSize, y: newSize }];
      return newItesm;
    });
  }, 1000);

  return (
    <div>
      Items:
      <ul>
        {items.map((item) => (
          <li>
            x: {item.x}, y: {item.y}
          </li>
        ))}
      </ul>
    </div>
  );
}

const rootElement = document.getElementById("root");
const root = ReactDOM.createRoot(rootElement);

root.render(<App />);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>

<div id="root"></div>

相关问题