在react native中检查和未检查不起作用



我对原生反应完全陌生,我不知道这是否是正确的方法。我正在使用@react-native-community/checkbox中的复选框组件。我正在从API获取一套服务。在那个APi中,我默认得到isCheked = false。当我点击复选框时,它工作正常,当取消选中时,它不工作。我不知道哪里出了问题。

import React, {useState, useEffect} from 'react';
import {Text, View, Picker, ScrollView, TouchableOpacity} from 'react-native';
import CheckBox from '@react-native-community/checkbox';
import {apiUrl} from '../../utilities/index';
import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from 'axios';
const BookingCreate = ({route, navigation}) => {
const [services, setServices] = useState([]);
useEffect(() => {
axios
.get(apiUrl + `salonService/salonID/${route.params.salonId}`, {
headers: {
auth: await AsyncStorage.getItem('token'),
'Content-Type': 'application/json',
},
})
.then((res) => {
setServices(res.data.servicesList);
})
.catch((e) => {
alert(e);
});
}, [route.params.salonId]);
const changeCheckboxValue = (id) => {
const data = services;
const index = data.findIndex((x) => x._id === id);
data[index].isChecked = data[index].isChecked ? false : true;
setServices(data);
};
return (
<View style={{flex: 1}}>
{services.length != 0 ? (
services.map((item) => (
<View>
<TouchableOpacity
style={{flexDirection: 'row'}}
onPress={() => changeCheckboxValue(item._id)}>
<CheckBox
value={item.isChecked}
onAnimationType="fill"
offAnimationType="fade"
boxType="square"
onValueChange={() => changeCheckboxValue(item._id)}
/>
<Text style={{marginLeft: 10}}>{item.serviceId.name}</Text>
<Text style={{marginLeft: 10}}>{item.category}</Text>
<Text style={{marginLeft: 10}}>{item.price}</Text>
</TouchableOpacity>
</View>
))
) : (
<Text>Loading</Text>
)}
</View>
)
}
export default BookingCreate;

问题

你的问题似乎是状态突变。您正在更改状态对象和特定索引处的嵌套属性,然后将相同的状态保存回,这是一个非操作。

const changeCheckboxValue = (id) => {
const data = services; // <-- state reference
const index = data.findIndex((x) => x._id === id);
data[index].isChecked = data[index].isChecked ? false : true; // <-- mutation!
setServices(data); // <-- state reference back to state
};

解决方案

使用功能状态更新来浅层复制您的状态。将上一个状态映射到下一个状态,当元素id匹配时,还可以浅层复制该元素并更新checked属性。实际上,您不需要首先在data数组中搜索索引,可以在将状态复制到下一个状态时对其进行一次迭代。

const changeCheckboxValue = (id) => {
setServices((data) =>
data.map((el) => // <-- copy state
el.id === id
? {
...el, // copy element to update
isChecked: !el.isChecked // toggle checked state
}
: el
)
);
};

最新更新