내 옵션 리스트는 위와 같이 생겼다. 나는 여기서 선택한 카테고리들을 다 category list에 추가하고 싶었다. 하지만 아래와 같은 코드를 작성했을 때는 계속 마지막으로 선택한 카테고리 하나만 리스트에 들어갔다.
var categoryList = []
const handleCategoryChange = (categories) => {
categoryList.push(categories)
setCategories(categories);
};
렌더링 될 때마다 값이 초기화되서 그런 것 같아서 useState를 써준 후
const [categoryList, setCategoryList] = useState([]);
const updatedCategoryList = [...categoryList, selectedCategory];
전에 있던 카테고리 리스트와 이번에 선택된 카테고리를 추가하도록 작성했다. 하지만 이렇게 하면
처음 인문학을 선택하면 [인문학]이렇게 저장되는데, 다음에 과학을 선택하면 [인문학, 인문학, 과학] 이렇게 저장된다.
그래서 if문을 넣어주었다.
const handleCategoryChange = (selectedCategorie) => {
// check if categories are duplicated, add them to the list if they are not duplicated
if (!categoryList.includes(selectedCategorie)) {
const updatedCategoryList = [...categoryList, selectedCategorie];
setCategoryList(updatedCategoryList);
}
setCategories(selectedCategorie);
};
그랬더니 하나씩 잘 저장되는 것을 확인하였다.
'웹 > React' 카테고리의 다른 글
[React] 책 검색 필터 변경 시 currentpage가 1로 이동되지 않음 (0) | 2023.09.26 |
---|---|
[React] 검색텍스트 입력 후 버튼 누르면 검색되게 하기, react에서 입력값 가져오기 (0) | 2023.09.21 |
[React] 흐르는 텍스트 시작 지점 설정 (0) | 2023.09.17 |
[React] useEffect set state가 바로 적용 안 되는 현상 (0) | 2023.09.15 |
[React/에러] TypeError: Cannot read properties of undefined (reading 'map') (0) | 2023.09.11 |
댓글