【问题标题】:react usestate Error: Too many re-renders. React limits the number of renders to prevent an infinite loop反应使用状态错误:重新渲染太多。 React 限制渲染次数以防止无限循环
【发布时间】:2021-10-20 20:46:15
【问题描述】:

如何解决此“重新渲染过多”错误?
我正在使用 try、catch 方法、useState、setState 反应钩子。
我正在尝试从 api 获取数据并在网络上打印。
此处出现错误:setEmoticonThm(newEmoticonThms)
错误:重新渲染过多。 React 限制渲染次数以防止无限循环。

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>
)

我添加了我的代码。 我怎样才能正确? TT

【问题讨论】:

  • 你在哪里打电话给getToken?您能否提供完整的代码,因为这是不可重现的。
  • @SinanYaman 我编辑了代码。感谢您的评论。
  • 你在哪里使用emoticonThm状态?
  • 恐怕您没有提供可重现的代码。现在我们必须看到handleKeyboardOpen 函数?你在其他地方使用setEmoticonThm 吗?
  • 我添加了代码。 handleKeyboardOpen 函数很简单。它只是改变状态。

标签: javascript reactjs


【解决方案1】:

onClick = {()=&gt;setSelectedThm(index)}代替onClick={setSelectedThm(index)}

onClick={setSelectedThm(index)} 导致重新渲染过多,函数在渲染阶段被调用。无需直接调用函数,只需传递函数的引用即可。

【讨论】:

    猜你喜欢
    • 2020-09-11
    • 2021-05-17
    • 2021-02-04
    • 2021-07-01
    • 2021-10-21
    • 2022-12-06
    • 2021-04-06
    • 2020-08-06
    • 2021-10-21
    相关资源
    最近更新 更多