본문 바로가기

FE/React

배열을 useState에서 사용할 때

const Main = () => {
  const [test, setTest] = useState([1, 2, 3]);

    function TestFunction({state, setState}): JSX.Element {
        return (
          <div
            style={{
              border: '1px solid black', height: '100px', width: '100%', display: ' block',
            }}
            onClick={() => {
              const qwer = state;
              qwer[2] -= 1;
              setState(qwer);
    
              console.log('clicked', state);
            }}
          >{test}
          </div>
        );
      }
    
    return (
        <TestFunction state={test} setState={setTest} />
    );
}

div 영역을 클릭하면 test 배열의 2번값이 -1 되어, 

클릭할 때마다 -1이 감소된 값이 리렌더될 것으로 생각되지만 .. 작동하지 않는다.


spread operator 를 사용하여

const asdf = [...state]; 이렇게 바꿔주어야한다는데 ..

 

원리는 시간나면 알아보도록 하자

 

https://stackoverflow.com/questions/68887710/using-array-as-react-hook-usestate

'FE > React' 카테고리의 다른 글

useState 가 아무튼 안될 때  (0) 2021.10.18
(React.js + Next.js) Skeleton 적용  (3) 2021.07.30
functions are not valid as a react child  (1) 2021.05.18
useEffect dynamic depth  (0) 2021.05.13