【发布时间】: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