简体   繁体   中英

React Child Component Not Rendering After Change

I am new to React and am trying to create my own scrollbar. I am using a local JSON API to simulate getting data which is then listing the data as 'cards'. I built a couple of other components to organize and handle the information, it looks like this:

Scrollbar (Buttons to Navigate)
 |-->CardList (Handles iterating over the cards)
        |-->Cards (Template for displaying an individual card) 

The issue I am having is that when I trigger the Button event handleNext it will successfully update offset & limit and pass these to CardList . However, it does not reiterate over the array and output the next 5 items. Instead it removes all the Cards from CardList and I am left with an empty screen.

Scrollbar.js:

    const { data isPending, error} = useFetch ('http://localhost:8000/data');
    const [limit, setLimit] = useState(5);
    const [offset, setOffset] = useState(0);


    const handleNext = () => {
      setOffset(offset + limit);

      console.log("Offset: " +offset);
    }

    return (  
        <div className="scrollbar">
                {error && <div>{error}</div>}
                {isPending && <div>Loading...</div>}
                {data && <CardList data={data} offset={offset} limit={limit}/> }
                
                <Button onClick={handleNext}/>
         </div>
   );
}
 
export default Scrollbar;

CardList.js:

const CardList = ({data , offset, limit}) => {

    return ( 

        <div className="card-list" >
            {data.slice(offset,limit).map((data) => (
                <Card data={data} key={data.id}/> 
            ))}
    </div>
     );
}
 
export default CardList;

The problem is when handleNext is triggered offset is going to be equal to 5 while limit keeps the value of 5 too, then when u do slice(offset,limit) is going to be replaced by slice(5,5) that returns an [] . What u want is increasing the limit too if u increase the offset , for example:

const handleNext = () => {
  setOffset(offset + limit);
  setLimit(limit + limit)
}

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