问题描述
我想我知道这个问题,但是我没有解决办法, 所以我有这些按钮是在useState arrray上循环创建的
const [booleanMonth,setMonth]=useState([
{key:0,value:'January',title:'Jan',checked:false},{key:1,value:'February',title:'Feb',{key:2,value:'march',title:'Mar',{key:3,value:'April',title:'Apr',{key:4,value:'May',title:'May',{key:5,value:'June',title:'Jun',{key:6,value:'July',title:'Jul',{key:7,value:'August',title:'Aug',{key:8,value:'September',title:'Sep',{key:9,value:'October',title:'Oct',{key:10,value:'November',title:'Nov',{key:11,value:'December',title:'Dec',checked:false}
])
然后渲染按钮:
const createButtonMonth = useMemo(() =>{
console.log('createButtonMonth')
return (<View style={styles.containerForButtons2}>
{
booleanMonth.map((item,key) =>
<View key={item.key} style={styles.buttonFilter3}>
<Button style={styles.buttonFilter3}
title={item.title}
value={booleanMonth[item.key].checked}
onCheckColor='red'
color={booleanMonth[item.key].checked==true ? 'green':'black'}
onPress={()=>onPressMonthFilter(booleanMonth[item.key].key,booleanMonth[item.key].checked)}
/></View>)
}
</View>)
},[booleanMonth])
现在这是onPress函数,它将检查状态更改为true或false,因此应该 更改这些按钮的颜色
const onPressMonthFilter = (keyMonth,statusMonth) =>{
if(booleanMonth[keyMonth].checked==true){
booleanMonth[keyMonth].checked=false
console.log(booleanMonth)
setMonth(booleanMonth)
}else{
booleanMonth[keyMonth].checked=true
console.log(booleanMonth)
setMonth(booleanMonth)
}
setMonth(booleanMonth)
}
在控制台日志中,它返回带有选中的true或false,这表示我的代码是正确的,但是没有呈现正确的颜色,false = black,true = green
解决方法
我认为是由于记忆。
尝试删除useMemo,因为它会捕获组件并阻止其重新呈现。