Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React 세미나 1 update함수 오류 #217

Open
TheoLee72 opened this issue Sep 14, 2022 · 2 comments
Open

React 세미나 1 update함수 오류 #217

TheoLee72 opened this issue Sep 14, 2022 · 2 comments
Labels
html / css / js javascript 관련 내용 question 질문으로 사용될 이슈 React React 관련 내용
Milestone

Comments

@TheoLee72
Copy link
Collaborator

이번과제 관련해서 코드 질문이 있습니다!

이번 과제 할때 todolist 연습용으로 올려주신 코드를 많이 참고했는데요 왜그런지 모르는 오류가 자꾸 생겨서요... 특정 메뉴를 클릭하면 선택 상태가 되게하고 만약 그 상태에서 다른 특정메뉴를 클릭하면 원래 선택상태의 메뉴는 선택이 풀리고 그 다른 특정메뉴가 선택상태로 바뀌는 것을 구현하려고 합니다.
image
이처럼 isselected를 따로 만들고

image
updateMenu 함수도 만들고

image
onClick에 menus.map해서 하나하나 none 만들고나서 그 클릭한것만 selected해줄려고 했는데
이상하게 가장 마지막 selected로 바꾸는것만 되고 앞에서 모든걸 none으로 만들어 주는 부분이 안되네요

@TheoLee72 TheoLee72 added React React 관련 내용 html / css / js javascript 관련 내용 labels Sep 14, 2022
@TheoLee72 TheoLee72 added this to the seminar-1 milestone Sep 14, 2022
@joongwon joongwon added the question 질문으로 사용될 이슈 label Sep 14, 2022
@joongwon
Copy link
Contributor

joongwon commented Sep 14, 2022

간단히 말하면 setMenus를 여러번 호출해서 생긴 문제입니다.

setMenus를 호출하더라도 당장은 menus의 값이 변하지 않습니다. (정확히는 update 함수에서 캡처한 menus 변수의 값이 불변입니다) menus라는 변수가 담고 있는 값은 언제까지나 이전 렌더링에서 얻은 값입니다. 때문에 실제 setMenus 호출은 아래와 같이 이루어집니다.

setMenus(이전 리스트에서 1번 메뉴가 선택 해제된 리스트)
setMenus(이전 리스트에서 2번 메뉴가 선택 해제된 리스트)
setMenus(이전 리스트에서 3번 메뉴가 선택 해제된 리스트)
...
setMenus(이전 리스트에서 id번 메뉴가 선택된 리스트)

최종적으로는 가장 마지막에 호출한 setMenus만 적용됩니다. 그러면 나머지 선택 해제된 값은 전부 무시되고 마지막에 메뉴가 추가로 선택된 리스트만 남게 됩니다.

해결 방법은 간단합니다. 모든 업데이트를 적용한 한 번의 setMenus만 호출해주시면 됩니다. 이를테면 아래 코드처럼 짤 수 있습니다.

예시 코드

setMenus(menus
    .map((m) => ({
        ...m,
        isselected: m.id === menu.id ? "selected" : "none"
    })));

@joongwon
Copy link
Contributor

질문 올려주셔서 감사합니다. 다만 앞으로 코드는 복붙해서 ```codes```로 감싸주시기 바랍니다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
html / css / js javascript 관련 내용 question 질문으로 사용될 이슈 React React 관련 내용
Projects
None yet
Development

No branches or pull requests

2 participants