React Native中@react-native-community/checkbox无法取消勾选问题求助
问题原因
isChecked函数没有添加return语句,执行后永远返回undefined,CheckBox组件无法拿到正确的勾选状态,所以会出现状态更新后视图不跟随变化的问题。- 状态更新直接依赖当前的
checkList变量,在列表渲染的回调场景下容易触发闭包陷阱,拿到过期的旧状态,导致更新异常。 - 原代码还缺失了
useState的导入语句,也可能引发运行报错。
修复方案
完整修复后的代码如下:
import { useState } from 'react'; import CheckBox from '@react-native-community/checkbox'; import { useRoute, useNavigation } from '@react-navigation/native'; export const ActionsScreen = () => { const route = useRoute<ActionScreenRouteProp>(); const params = route.params; const { actionList, eventType, emergencyRole } = params const [checkList, setCheckList] = useState<any[]>(actionList.map(e => ({ key: e.key, checked: false }))); // 补全return语句,用find替代filter优化查询性能,同时添加兼容逻辑避免匹配不到key时报错 const isChecked = (key) => { return checkList.find(e => e.key == key)?.checked ?? false } const renderActionItem = ({ item, index }) => { return ( <TouchableOpacity key={index} activeOpacity={.7} style={styles.touchableOpacity} onPress={() => { console.log(item) }} > <CheckBox style={styles.checkBox} tintColors={{ true: 'white', false: 'white' }} value={isChecked(item.key)} // 改用函数式更新获取最新状态,避免闭包导致的状态更新异常 onValueChange={() => { setCheckList(prev => prev.map(e => { if (e.key == item.key) { return {...e, checked: !e.checked} } return e })) }} /> <Text style={styles.labelText}>{`${item.sequenceID}. ${item.label}`}</Text> </TouchableOpacity> ) } return ( <SafeAreaView style={styles.container}> <FlatList style={styles.flatListView} data={actionList} keyExtractor={(item, index) => index.toString()} renderItem={renderActionItem} /> </SafeAreaView> ); }
内容的提问来源于stack exchange,提问作者emma
相关产品推荐
相关产品推荐

