React Native条件渲染持续重复渲染问题求助
问题:React Native模板切换时渲染次数过多、功能异常
希望通过点击按钮切换显示不同模板,默认选中「One-Time」模板。使用布尔状态值和回调函数切换状态,但出现模板渲染次数过多的问题,功能无法正常运行。
原代码
import React, {useState} from 'react'; import {Button, Text, View} from 'react-native'; export default function TabTwoScreen() { const [showOneTime, setShowOneTime] = useState(true); const showTemplate = (template: string) => { if(template == 'OneTime') setShowOneTime(true); else setShowOneTime(false); } const renderOneTimeTemplate = () => { return ( <View> <View> <Button onPress={showTemplate("OneTime")} title='One-Time' /> <Button onPress={showTemplate("Recurring")} title='Recurring' /> </View> <Text>OneTime Template</Text> </View> ); } const renderRecurringTemplate = () => { return ( <View> <View> <Button onPress={showTemplate("OneTime")} title='One-Time' /> <Button onPress={showTemplate("Recurring")} title='Recurring' /> </View> <Text>Recurring Template</Text> </View> ); } return ( (showOneTime && renderOneTimeTemplate()) || (!showOneTime && renderRecurringTemplate()) ); }
问题原因
核心错误是Button的onPress属性直接执行了函数,而不是传递函数引用。比如onPress={showTemplate("OneTime")}会在组件每次渲染时立即调用showTemplate,触发状态更新,进而导致组件重新渲染,形成无限循环,最终引发渲染次数过多的问题。
修正方案
- 把
onPress的写法改成箭头函数包裹,确保只有点击按钮时才执行showTemplate - 抽离重复的按钮组,避免代码冗余
修正后的代码
import React, {useState} from 'react'; import {Button, Text, View} from 'react-native'; export default function TabTwoScreen() { const [showOneTime, setShowOneTime] = useState(true); const showTemplate = (template: string) => { setShowOneTime(template === 'OneTime'); }; // 抽离重复的按钮组件 const renderTemplateTabs = () => ( <View> <Button onPress={() => showTemplate("OneTime")} title='One-Time' /> <Button onPress={() => showTemplate("Recurring")} title='Recurring' /> </View> ); return ( <View> {renderTemplateTabs()} {showOneTime ? <Text>OneTime Template</Text> : <Text>Recurring Template</Text>} </View> ); }
修改后,按钮点击才会触发状态更新,组件不会陷入无限渲染循环,同时代码结构更简洁。
内容的提问来源于stack exchange,提问作者xccelerated99
相关产品推荐
相关产品推荐

