❗️Error/오류를 해결하자!

A component is changing a controlled input of type number to be uncontrolled.

hellohailie 2022. 8. 8. 07:33

 

Warning: A component is changing a controlled input of type number to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

 

문제 원인

useState 안의 값으로 title, amount 값 이렇게 2개를 받는데, onChange 함수에서는 각각 하나씩만 설정해주고 있다. 

그래서 이 에러창이 나오는 것 같다. 

 

 

해결방법 

다른 값은 바꿀 필요가 없기 때문에 현재값을 넣어주었다. 


 

기존 코드

const [inputState, setInputState] = useState({ title: "", amount: "" });

<input type='text'id='title'value={inputState.title}
onChange={(event) =>  setInputState({title: event.target.value})} />

<input type='number' id='amount' value={inputState.amount}
onChange={(event) =>setInputState({amount: event.target.value})}/>

 

 

수정코드

const [inputState, setInputState] = useState({ title: "", amount: "" });

<input type='text'id='title'value={inputState.title}
onChange={(event) =>  setInputState({title: event.target.value, amount: inputState.amount})} />

<input type='number' id='amount' value={inputState.amount}
onChange={(event) =>setInputState({amount: event.target.value, title: inputState.title})}/>

👆어쩌면 최신 업데이트된 상태를 못가져올 수도 있다. 

 

 

더 좋은 수정코드

const [inputState, setInputState] = useState({ title: "", amount: "" });

<input type='text'id='title'value={inputState.title}
onChange={(event) => {
const newTitle = event.target.value;
setInputState((prevInputState) => ({title: newTitle, amount: prevInputState.amount}))}} />

<input type='number' id='amount' value={inputState.amount}
onChange={(event) => {
const newAmount = event.target.value;
setInputState((prevInputState) => ({amount: newAmount, title: prevInputState.title}))}}/>

👆 완벽하게  최신 업데이트된 상태를 가져온다.