React Hooks Update Dictionary State
(https://stackoverflow.com/questions/63122527/react-hooks-update-dictionary-state)
I have a state that should be a dictionary like so:
[personInfo, setPersonInfo] = useState({"firstName": "", "lastName": ""});
I want to update this state like so:
setPersonInfo(prevPersonInfo => prevPersonInfo["firstName"] = "name")
But this is not working.
Please do not recommend that I store two separate states for firstName and lastName. For my particular use case, it is necessary that I use a dictionary.
答えが見つからない?日本語で聞いてみましょう。
My guess is that it isn't working because you are altering the same object, instead of returning a new one. I'd recommend rewriting it in a way that spreads into a new object
setPersonInfo(prevPersonInfo => ({...prevPersonInfo, firstName: "name"}))
Incidentally, depending on how complex your object is getting you might want to consider useReducer
.
'frameworks > react' 카테고리의 다른 글
Publisher subscriber pattern(포스트 하단에 코드가 움직이는 순서 정리) (0) | 2021.05.18 |
---|---|
useRef 이해하기, useRef의 두 가지 기능: 1. Dom제어 2. re-render시에도 격납한 값이 불변 (0) | 2021.03.25 |
벨로퍼트와 함께하는 모던 리액트 강의(https://react.vlpt.us/) (0) | 2021.02.18 |
footer 하단 고정 (간단!) (0) | 2020.09.22 |
React + ESLint + airbnb + vscode 세팅 (1) | 2020.09.13 |
setPersonInfo(ppi => ({...ppi, firstName: 'name'}))
– George Jul 27 '20 at 19:52setPersonInfo(prev => {...prev, firstName: 'SOME_NAME'})
– AngelSalazar Jul 27 '20 at 19:52