在React JS中使用一些渲染数组元素

时间:2020-10-20 14:55:05

标签: javascript arrays reactjs react-native react-hooks

我在React JS中有一个包含字符串数据的数组,我想遍历该数组并以一定的延迟呈现该数组的每个元素。 我已经尝试过setTimeout,setInterval,但这些方法都不适合我。

相反,我所做的是将该数组移到另一个数组中,然后将其放入setTimeout中,因此可能要花一些时间,但对我而言不起作用

这是代码

const [index, setIndex] = useState(0);
const [shiftArr, setShiftArr] = useState([]);
const fruitsArray = [
    "Apple",
    "Banana",
    "Mango",
    "Grapes",
    "Peach",
    "Avocado",
    "watermelon",
    "Pineapple",
    "Orange",
    "Strawbries",
  ];

useEffect(() => {
      
    for (let i = 0; i < fruitsArray.length; i++) {
      setTimeout(() => {
        setShiftArr((shiftArr) => [...shiftArr, fruitsArray[i]]);
        setIndex(i + 1);
      }, 2000);
    }
  }, []);

渲染移位数组

<div className="fruitList">
          {shiftArr.map((fruit, ind) => (
            <div style={{ marginLeft: "20px" }} key={ind}>
              {fruit}
            </div>
          ))}
        </div>

1 个答案:

答案 0 :(得分:2)

设置状态后,将重新呈现Component,如果依赖关系发生更改,则会再次调用useEffect

使用shiftArr作为useEffect的依赖项,如果它的长度与原始数组不同,则设置超时时间,并通过切片将其从原始数组中创建shiftArray包括下一项:

const { useState, useEffect } = React;

const Demo = ({ array }) => {
  const [shiftArr, setShiftArr] = useState([]);
  
  // initialize the shiftArr when array changes
  useEffect(() => setShiftArr(array.slice(0, 1)), [array]);
  
  useEffect(() => {
    if(shiftArr.length === array.length) return;
    
    const timeout = setTimeout(() => 
      setShiftArr(array.slice(0, shiftArr.length + 1))
    , 2000);
    
    return () => clearTimeout(timeout);
  }, [shiftArr]);

  return (
    <div className="fruitList">
      {shiftArr.map((fruit, ind) => (
        <div style={{ marginLeft: "20px" }} key={ind}>
          {fruit}
        </div>
      ))}
    </div>
  );
};

const fruits = ["Apple","Banana","Mango","Grapes","Peach","Avocado","watermelon","Pineapple","Orange","Strawbries"];

ReactDOM.render(
  <Demo array={fruits} />,
  root
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

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