简体   繁体   中英

useState create infinite loop

I am creating a web application with next and tailwind, I need to pass a series of data between methods for which I am using a useState, but when loading it keeps loading with ridiculous RAM usage and never charges.

Component:

export default function Home({ nav, footer, content, edition }) {

const [activeEdition, setActiveEdition] = useState({
 background: '',
 title: '',
 prize: '',
 sponsors: [], 
});

return (
 <div>
  
  {edition.map((result) => {
    
    const { data } = result;  

    if(data.active){
      setActiveEdition({
        background: data.edition_background.url,
        title: data.edition_title,
        prize: data.prize.url,
        sopnsors: data.body[0].items,
      });
    }

    return (
      null
    )
  })}

  {content.map((result) => {
    const active = activeEdition
    const { data } = result

    return (
      <Hero
        key = {data.id}
        active = {active}

      />
    )
  })}
  
</div>
 );
}

Implementation:

function Hero({heroData, active, register}) {
    const background = {
        backgroundImage: `url('${active}')`
    }
    
    console.log(active)

    return (
        <div>
            <h1>asdas</h1>
        </div>
    )
}

export default Hero

Update: complete compnent added for a better understanding

Move the map into useEffect hook, also no need for map since you don't transform data, just iterate and make a change based on the value. Also added a break since I assume only one item will match the criteria.


useEffect(() => {
  for (const result of edition) {

    const { data } = result;  

    if(data.active){
      setActiveEdition({
        background: data.edition_background.url,
        title: data.edition_title,
        prize: data.prize.url,
        sopnsors: data.body[0].items,
      });
      break;
    }

  }}, [edition]);

Like I mentioned in the comment: you are creating an infinite loop because you modify state upon render. What you want is to update state based on edition changes. This side effect is supposed to be done in useEffect.

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