카테고리 없음

[react] key를 이용해 상태 초기화

ehddkDEV 2025. 3. 3. 14:43

이 textinput에 값을 입력하고 추가 버튼을 누르면 해당 필드 값이 초기화가 되어야하는데!!
자꾸 안되는거다... 이전 값이 남아있다.. 

그래서 어디에서 막힌건지 콘솔값을 찍어봤을때 입력하고 추가버튼을 누르면 ""로 초기화가 잘되고 있는 것 같은데 필드에는 여전히 남아있는 이슈..,,

 

 const handleKeywords = () => {
    if (keyword.trim() === "") {
      //  console.log("키워드가 비어 있음");
      return;
    }
    if (!keywords.includes(keyword)) {
      const newKeywords = [...keywords, keyword];
      setKeywords(newKeywords);
      form.setValue("keywords", newKeywords);

      setKeyword("");

    }
  };

이렇게 setKeyword("")로 해주면 초기화가 되는 줄 알았는데 ?

 

구글링을 해보니 react의 Key 속성을 이용해 아예 컴포넌트를 분리해줄 수 있는 것 같다.

const [inputKey, setInputKey] = React.useState(0);

  const handleKeywords = () => {
    if (keyword.trim() === "") {
      //  console.log("키워드가 비어 있음");
      return;
    }
    if (!keywords.includes(keyword)) {
      const newKeywords = [...keywords, keyword];
      setKeywords(newKeywords);
      form.setValue("keywords", newKeywords);

      setKeyword("");
      setInputKey((prev) => prev + 1);
    }
  };
  
  
  return(
     <TextInput.Root key={inputKey}>
     <TextInput.Input
         placeholder="추가할 키워드를 입력해 주세요."
         value={keyword}
         onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
            setKeyword(e.target.value);
          }}
      ></TextInput.Input>
      </TextInput.Root>
  )

이렇게 prev + 1 을 함으로써 이전 key를 변경하여 컴포넌트 리셋시키는 방식!