[英]How can I map through an array of objects, remove one and set my state as the new array in react-native?
I have a list of checkboxes representing calendars.我有一个代表日历的复选框列表。 When a checkbox is clicked, the respective calendar is added to my state
checkedTaskList
as an array.单击复选框时,相应的日历将作为数组添加到我的状态
checkedTaskList
中。
How can I map through this checkedTaskList
array, and remove a calendar from it when it is unchecked?如何映射此
checkedTaskList
数组,并在未选中时从中删除日历? I wish to then set my state with the new array with the unchecked calendar removed.然后,我希望使用删除了未经检查的日历的新数组设置我的状态。
STATE状态
const [checkedTaskList, setCheckedTaskList] = useState([]);
CALENDAR CHECKBOXES日历复选框
<CheckBox_1 checked={() => setTaskCheked(calendar)} /> //Holidays
<CheckBox_1 checked={() => setTaskCheked(calendar)} /> //Birthdays
<CheckBox_1 checked={() => setTaskCheked(calendar)} /> //Events
setTaskCheked FUNCTION setTaskChecked 函数
const setTaskCheked = (calendar) => {
if (checkedTaskList.length > 0) { //CHECK IF ARRAY IS EMPTY
const tempCalendarList = checkedTaskList;
tempCalendarList.map((cal) => {
if (cal === calendar) { //CHECK IF SELECTED CALENDAR IS ALREADY IN checkedTaskList STATE
const index = tempCalendarList.indexOf(cal);
tempCalendarList.slice(index, 1);//REMOVED UNCHECKED CALAENDAR
setCheckedTaskList(tempCalendarList);//SET STATE WITH NEW ARRAY WITH REMOVED CALENDAR
}
});
} else {
setCheckedTaskList([...checkedTaskList, calendar]);
}
};
You can use Array.prototype.filter()
to get all other elements.您可以使用
Array.prototype.filter()
来获取所有其他元素。
const setTaskCheked = (calendar) => {
if (checkedTaskList.length > 0) {
setCheckedTaskList(checkedTaskList.filter(cal => cal != calendar)
} else {
setCheckedTaskList([...checkedTaskList, calendar]);
}
};
Like Balastrong said, first use filter to remove the unchecked element, which you confirmed works.就像 Balastrong 说的那样,首先使用过滤器删除未选中的元素,您确认该元素有效。
What I'm assuming you're doing next is checking the array right after setting it, sorta like我假设你接下来要做的是在设置数组后立即检查它,有点像
setCheckedTaskList([...checkedTaskList, calendar]);
alert(checkedTaskList.length);
and this would show you the checkedTaskList's previous contents, as the call to set it is asynchronous.这将显示checkedTaskList 以前的内容,因为设置它的调用是异步的。
To more accurately see the changes, you will need to utilize useEffect() and hook into the checkedTaskList, like为了更准确地查看更改,您需要使用 useEffect() 并挂钩到 checkedTaskList,例如
useEffect(() => {
if (checkedTaskList.length > 0)
alert(checkedTaskList.length);
}, [checkedTaskList]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.