简体   繁体   中英

react usestate Error: Too many re-renders. React limits the number of renders to prevent an infinite loop

How do I fix this 'Too many re-renders' error?
I'm using try, catch method, useState, setState react hooks.
I'm trying to get data from api and print on web.
Error occurs here: setEmoticonThm(newEmoticonThms)
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

const [emoticonThm, setEmoticonThm] = useState([]);
const getToken = async () => {
  try {
    const emoticon = await axios.get(`${process.env.EMOTICON_ENDPOINT}`, {
      headers: {
        Authorization: accessToken
      }
    })
    let newEmoticonThms = []
    emoticon.data.emoticonPacks.map( (emoticon) => {
      newEmoticonThms.push({
        id: emoticon.id,
        image:url + emoticon.image
      })  
    })
    setEmoticonThm(newEmoticonThms)
  } catch (err) {
    console.log(err)
  }
}
const onClickSticker = () => {
  getToken()
  handleKeyboardOpen()
}

return (
 ...
 <Sticker onClick={onClickSticker}/>
 <TabContainer>
      {emoticonThm.map((emoticon, index) => {
           return (
                <EmoticonThmButton 
                     key={index}
                     onClick={setSelectedThm(index)}
                 >
                      <EmoticonThmImage
                           key={index}
                           onClick={onEmoticonClick}
                           src={img}
                      />
                 </EmoticonThmButton>
           )
        })}
 </TabContainer>
)

I added my code. How can I get it right? TT

Instead of onClick={setSelectedThm(index)} do onClick = {()=>setSelectedThm(index)}

onClick={setSelectedThm(index)} is causing too many rerenders, the function gets called on the rendering phase. Instead of directly calling the function, you just pass the reference of the function.

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