Работа с React Hooks (useEffect, useState) добавление и удаление элемента из массива переменной состояния
Возникла проблема, с удалением элементов массива в переменной состояния. При клике на кнопку элемент добавляется и при этом происходит изменение цвета кнопки, но при удалении элемента, цвет кнопки не меняется, но сам элемент удаляется.
const tags - [ "Драма", "Мистика", "Sci-Fi" ];
const TagsList = ({
searchResults,
setSearchResult,
}) => {
const classes = useStyles();
const [activeButtonTags, setActiveButtonTags] = useState([]);
useEffect(() => {
// при каждом изменении activeButtonTags обновляем
// результирующий массив который отображается - searchResults
const findTags = searchResults.filter((item) => {
const findTagsTitle = item.tags.filter((itemTags) =>
activeButtonTags.includes(itemTags)
);
if (activeButtonTags.length === findTagsTitle.length) {
return item;
}
});
setSearchResult(findTags);
}, [activeButtonTags]);
const onChangeTags = (_tags) => {
// в findIndexTags получаем индекс тега из массива тегов activeButtonTags
// далее по индексу удаляем элемент
const findIndexTags = activeButtonTags.findIndex(
(item, index) => item === _tags
);
if (findIndexTags === -1) {
// если элемента нет, мы его добавляем
setActiveButtonTags([...activeButtonTags, _tags]);
console.log("onChangeTags added", activeButtonTags);
} else {
// если элемент уже есть, то удаляем его
activeButtonTags.splice(findIndexTags, 1);
setActiveButtonTags(activeButtonTags);
console.log("onChangeTags delete", activeButtonTags);
}
};
return ( <
>
<
List component = "nav"
className = {
classes.root
}
aria - label = "contacts" > {
tags.map((item, index) => {
if (index < 4) {
return ( <
Button key = {
index
}
onClick = {
() => {
onChangeTags(item);
// tagsFilter(item);
}
}
className = {
classes.button
}
variant = "contained"
style = {
{
backgroundColor: activeButtonTags.includes(item) ?
"#db7093" :
"gray",
}
} >
{
item
} <
/Button>
);
}
})
} <
/List> <
List component = "nav"
className = {
classes.root
}
aria - label = "contacts" > {
tags.map((item, index) => {
if (index > 3 && index < 8) {
return ( <
Button key = {
index
}
onClick = {
() => {
onChangeTags(item);
}
}
className = {
classes.button
}
variant = "contained"
style = {
{
backgroundColor: activeButtonTags.includes(item) ?
"#db7093" :
"gray",
}
} >
{
item
} <
/Button>
);
}
})
} <
/List> <
List component = "nav"
className = {
classes.root
}
aria - label = "contacts" > {
tags.map((item, index) => {
if (index > 7 && index < 12) {
return ( <
Button key = {
index
}
onClick = {
() => {
onChangeTags(item);
}
}
className = {
classes.button
}
variant = "contained"
style = {
{
backgroundColor: activeButtonTags.includes(item) ?
"#db7093" :
"gray",
}
} >
{
item
} <
/Button>
);
}
})
} <
/List> <
/>
);
};
export {
TagsList
};