简体   繁体   中英

Loop in React JSX

Instead of using fileList.map(), I want to put it in for loop and setTimeout(500) for every single loop. How can I do it?

 const SortableList = SortableContainer(({ fileList }) => (
      <div>
        {
        fileList.map((file, index) => (
          <SortableItem key={`item-${index}`} index={index} value={file} />
        ))
        }
      </div>
    ))

You can do something like this:

import React, {useState, useEffect} from 'react';

const ITEMS_TO_ADD_IN_EACH_TIMEOUT = 50

const SortableList = SortableContainer(({ fileList }) => {
   const [visibleItems, setVisibleItems] = useState([])

   useEffect(() => {
      const timer = setTimeout(() => {
          setVisibleItems([fileList.slice(0, visibleItems.length + ITEMS_TO_ADD_IN_EACH_TIMEOUT)])
      }, 500);

      return () => clearTimeout(timer);
   })

   return (
      <div>
         {
            visibleItems.map((file, index) => (
              <SortableItem key={`item-${index}`} index={index} value={file} />
            ))
         }
      </div>
   ))
}

A very simple way is to create a new array which should contain the items which are currently visible.

Then do a simple setTimeout which will call a recursive function every 500ms that will add one element to the visible array.

 const SortableList = SortableContainer(({ fileList }) => {
  const [visibleItems, setVisibleItems] = useState([]);
  useEffect(() => {
    function displayNext(next) {
      setVisibleItems(prevItems => [...prevItems, fileList[next]]);
      if (++next < fileList.length) {
        setTimeout(() => {
          displayNext(next);
        }, 500);
      }
    }

    displayNext(0);
  }, []);

  return (
     <div>
        {
           visibleItems.map((file, index) => (
             <SortableItem key={`item-${index}`} index={index} value={file} />
           ))
        }
     </div>
  )});

Let me know if works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM