You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React使用useState出现Too many re-renders错误,i18n-next多语言项目如何解决?

报错根本原因
  • 你在组件的渲染返回块中直接调用了setLang状态更新方法,触发了无限重渲染循环:
    React组件每次渲染都会执行return内的所有逻辑,你写的supportedLanguages.map遍历逻辑没有返回任何要渲染的UI,反而在每次遍历时执行setLang(index)。而只要调用setLang就会触发组件重新渲染,新的渲染又会再次执行遍历、再次调用setLang,无限循环后React就会抛出Too many re-renders. React limits the number of renders to prevent an infinite loop的错误。
  • 这段遍历逻辑本身也没有实际作用:遍历完两个语言选项后,lang状态最终只会被覆盖为最后一项的下标1,完全达不到存储选中语言下标的预期作用。
修复方案
  1. 首先删除return内冗余的遍历代码:
// 删掉这段无效代码
{supportedLanguages.map((option, index) => (
  setLang(index)
))}
  1. 你的两个按钮分别对应固定的语言下标,直接把下标写死在点击事件参数中即可,完全不需要用到lang这个多余的状态:
<button onClick={event => handleClickSelectLanguage(event, 0)}>English</button>
<button onClick={event => handleClickSelectLanguage(event, 1)}>French</button>

如果后续要扩展支持的语言,推荐直接遍历supportedLanguages生成按钮,避免硬写下标:

{supportedLanguages.map((langCode, index) => (
  <button key={langCode} onClick={event => handleClickSelectLanguage(event, index)}>
    {langCode === 'en' ? 'English' : 'French'}
  </button>
))}

内容的提问来源于stack exchange,提问作者user16050054

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 15:09:03