React处理嵌套map中的多个复选框

xe55xuns  于 2023-04-07  发布在  React
关注(0)|答案(1)|浏览(152)

尝试在嵌套Map中处理多个Checkbox.Android对象。
问题是,如果我例如检查第一个复选框的“练习一”也第一个复选框的“练习2”得到检查.我想,因为他们有相同的ID!?
exercises-Array:

{"id":1,"title":"Push Volume","exercises":[{"exercise_id":1,"exercise_sets":3},{"exercise_id":2,"exercise_sets":2}],"total_exercises":2]
const [checkedItems, setCheckedItems] = useState([]);

  const handleCheckboxChange = (id) => {
    const newCheckedItems = [...checkedItems];
    const index = newCheckedItems.indexOf(id);
    console.log({index});
    if (index === -1) {
      newCheckedItems.push(id);
      //setShowOverlay(true);
    } else {
      newCheckedItems.splice(index, 1);
      setShowOverlay(false);
    }
    
    setCheckedItems(newCheckedItems);
    
    
  };

  return (
    {map(exercises, (item, i) => (

        <Text style={{...innerStyles.item_subtitle, marginBottom:10}}>{item.exercise_title}</Text>

        {Array.from({ length: item.exercise_sets }).map((_, setIndex) => (
            <View style={{ flexDirection: 'row' }} key={setIndex}>
            <Text style={innerStyles.HeaderTitle} key={setIndex}>
                {Strings.ST82} {setIndex + 1} 
            </Text>
            
            
            <View style={{ flex: 1, justifyContent: 'center', marginLeft:20  }}>
                <Checkbox.Android
                    key={`Check-${item.exercise_id}-${setIndex}`}
                    color={ColorsApp.PRIMARY}
                    uncheckedColor={'#b9b9b9'}
                    status={checkedItems.includes(item.exercise_id && setIndex) ? 'checked' : 'unchecked'}
                    onPress={() => handleCheckboxChange(setIndex)}
                />
            </View>
            </View>
        ))}

    ))}
  )
6qftjkof

6qftjkof1#

通过使用(${item.exercise_id}-${setIndex})生成一个唯一密钥找到了解决方案

<Checkbox.Android
                    key={`Check-${item.exercise_id}-${setIndex}`}
                    color={ColorsApp.PRIMARY}
                    uncheckedColor={'#b9b9b9'}
                    status={checkedItems.includes(`${item.exercise_id}-${setIndex}`) ? 'checked' : 'unchecked'}
                    onPress={() => handleCheckboxChange(`${item.exercise_id}-${setIndex}`)}
                />

相关问题