React Native组件出现Too many re-renders错误,请求排查原因
问题原因
你遇到的无限重渲染问题,根源在于直接在组件渲染流程中调用了状态更新函数setShowList。
组件每次渲染时,都会执行if (currentList === ...)里的逻辑,调用setShowList会触发组件重新渲染。新的渲染又会再次执行这些条件判断,再次调用setShowList,形成了「渲染→触发更新→再渲染」的无限循环,React因此抛出了限制重渲染的错误。
解决方案
针对你的场景,有两种更合理的处理方式:
方案1:用useEffect监听currentList变化(适合需要维护状态的场景)
通过useEffect设置依赖项,只有当currentList改变时,才更新showList状态,避免每次渲染都触发更新:
import { exercisesList } from '-utils/exercisesList' import { knowHowList } from '-utils/knowHowList' import { useState, useEffect } from 'react' import { Text, View } from 'react-native' const ArticleView = ({ route }) => { const [showList, setShowList] = useState([]) const { itemId, currentList } = route.params useEffect(() => { if (currentList === 'exercisesList') { setShowList(exercisesList) } else if (currentList === 'knowHowList') { setShowList(knowHowList) } }, [currentList]) // 仅当currentList变化时执行 const currentArticle = showList.find((item) => item._id === itemId) || {} return ( <View> <Text>LIST:</Text> <Text>{currentArticle.title || '无内容'}</Text> </View> ) } export default ArticleView
额外说明:原代码中filter返回的是数组,直接取currentArticle.title会报错,改成find返回单个对象更合适,同时增加默认值避免空值问题。
方案2:直接计算值(更简洁,适合静态数据场景)
因为exercisesList和knowHowList是静态导入的常量,不需要存到状态里,直接根据currentList计算出目标列表即可,完全避免状态更新带来的重渲染问题:
import { exercisesList } from '-utils/exercisesList' import { knowHowList } from '-utils/knowHowList' import { Text, View } from 'react-native' const ArticleView = ({ route }) => { const { itemId, currentList } = route.params const showList = currentList === 'exercisesList' ? exercisesList : knowHowList const currentArticle = showList.find((item) => item._id === itemId) || {} return ( <View> <Text>LIST:</Text> <Text>{currentArticle.title || '无内容'}</Text> </View> ) } export default ArticleView
这种方式更高效,不需要维护额外的状态,直接在渲染时计算所需值即可。
内容的提问来源于stack exchange,提问作者Carlos del Río Francés
相关产品推荐
相关产品推荐

