-
nomad) react useState( [] ) 활용React 2023. 3. 17. 11:59
todo 리스트를 만들 때
const [ toDo, setToDo ] = useState( "" );
const [ toDos, setToDos ] = useState( [] ); 로 선언할 경우
배열로 초기값이 지정된 toDos 에 값을 추가하고 싶다면,
setToDos(currentArray => [ toDo, ...currentArray ]); 를 사용한다.
-> ...currentArray는 현재 currentArray 내부에 있는 값들을 모두 출력하는 명령어로,
위의 상태에서는 toDos 배열에 저장된 모든 값들을 출력한다고 할 수 있다.
따라서 기존에 있던 toDos 배열에 toDo 값을 지정해서 다시 toDos 배열에 저장하고자 한다.
- input에 넣고 submit 한 string이 toDos 배열에 저장된다.
const [ state , setState ] = useState() ; 에서
setState 는 기본적으로 초기값과 동일한 자료형을 가진다.
또한 setState는 조건으로 함수를 지정할 수도 있다.
setState( () => )
'React' 카테고리의 다른 글
OPEN API 데이터 불러오기 ( fetch ) (0) 2023.03.19 nomad) react .map( ) (0) 2023.03.17 nomard) Clean Up 함수 (0) 2023.03.16 nomard) React 설치 및 연결 (0) 2023.03.16 nomard) ReactJS 기본, useState, Component, props (0) 2023.03.13