从复选框数组中选中一个

Check one from the array of checkboxes

我的任务是从 URL 中加载一系列过敏,并为每个过敏构建一个复选框。虽然以某种方式在点击其中任何一个之后,复选框没有被选中,尽管底层过敏数组发生了变化并反映了“选中”属性的变化。我一定是忽略了一些微不足道的东西。

我的 React Native 组件:

import React, { useState, useContext, useEffect } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';
import { Button, CheckBox } from 'react-native-elements';
import { OnboardingContext } from "../context/onboarding_context";

export function AllergyScreen({ navigation }) {
  const [isLoading, setLoading] = useState(true);
  const [allergies, setAllergies] = useState([]);
  const [state, setState] = useContext(OnboardingContext);

  useEffect(() => {
    fetch('https://foodstuff.com/api/allergies.json')
      .then((response) => response.json())
      .then((json) => setAllergies(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, []);

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>CATEGORY: {state.category.name}</Text>
      <View style={{ flex: 1, padding: 24 }}>
          <FlatList
            data={allergies}
            keyExtractor={item => item.id.toString()}
            renderItem={({ item }) => (
              <CheckBox
                center
                title={item.name}
                checked={item.checked}
                onPress={() => {
                    item.checked = !item.checked;
                    Object.assign(allergies[allergies.findIndex(element => element.id === item.id)], item)
                    setAllergies(allergies);
                  }
                }
              />
            )}
          />
      </View>
    </View>
  );
}

过敏:

Array [
  Object {
    "checked": true,
    "created_at": "2020-11-14T10:35:18.883Z",
    "id": 1,
    "name": "Walnuts",
    "updated_at": "2020-11-14T10:35:18.883Z",
  },
  Object {
    "checked": false,
    "created_at": "2020-11-14T10:35:25.345Z",
    "id": 2,
    "name": "Avocado",
    "updated_at": "2020-11-14T10:35:25.345Z",
  },
  Object {
    "checked": false,
    "created_at": "2020-11-14T10:35:31.829Z",
    "id": 3,
    "name": "Bad people",
    "updated_at": "2020-11-14T10:35:31.829Z",
  },
]

试试这个方法

const onCheck = (index) => {
  const newData = [...allergies];
  newData[index].checked = !newData[index].checked;
  setAllergies(newData);

}   

renderItem={({ item, index }) => (
  <CheckBox
    ......
    onPress={() => { onCheck(index); }
    }
  />
)}