-
17. React [리액트 애플코딩] map매서드 리액트에 적용하기, JSX내에서의 반복문, props 복습하기Java Script & Type Script 2022. 12. 30. 20:40728x90
map매서드
- 왼쪽 array자료 요소의 갯수만큼 함수 안의 코드를 반복실행해줌
- 함수의 파라미터는 array안에 있던 자료
- Return에 뭘 적으면 array로 담아준다. 그리고 map()쓴 자리에 남겨준다.
알고리즘 풀 때부터 map은 써도 써도 완전히 이해하기 어려웠다.
map뒤에는 콜백함수가 따라 붙는다.
콜백함수라는 개념도 구글링을 아무리 해도 이해가 안됐는데, 코딩애플에서는 "소괄호 안에 들어가는 함수"라고 간단히 정리해주었다.
그렇게 생각하니 갑자기 쉽게 느껴지는 magic 😳
- 배열자료 요소의 갯수만큼 함수 안의 코드를 반복실행해준다.
[1,2,3].map(function(){ console.log(1) })
오.. 이렇게 보니 더 잘 이해된다.
배열.map (function(){})
맵 함수는 배열에있는 요소만큼 뒤에 따라오는 내용을 반복한다.
저걸 실행시키면 콘솔에 1이 세개 찍힌다.
이렇게 이해해볼 생각은 못해봤는데 코딩애플은 천잰가보다,,
2. 함수의 파라미터는 array내부의 요소가 된다.
콜백함수에 파라미터 아무렇게나 작명을 하면 그 파라미터는 어레이 안에 있던 모든 자료를 하나씩 출력해줌
함수의 파라미터에 입력한 a는 어레이 내부의 모든 요소가 된다. 그리고 a,i 를 파라미터로 입력하면 i는 인덱스가 되기도 한다.
function의 파라미터 ()소괄호 안에 a는 array안에 있던 하나하나의 데이터.
배열이름.map(function(a){
return (
…)
}
3. Return에 뭘 적으면 array로 담아준다. 그리고 map()쓴 자리에 남겨준다.
이게 무쓴 뜻? 이냐면,
보다시피 배열 [1,2,3] 의 요소는 세개이다.
map함수에서 파라미터 a가 배열의 요소 1,2,3가 될 것이고, return '123421'이 이제 각 요소에 반복하여 적용 될 것이다.
그래서 ['123421', '123421', '123421]
'123421'이 총 3번 반복하여 도출된다.
map을 이용해 이런 곱셈식도 만들 수 있다.
어레이라는 배열의 a파라미터는 내부에 존재하는 각 요소를 뜻하고, 10씩 곱해서 newArray를 선언.
newArray는 [20,30,40]이 출력됨.
JSX내에서 같은 html 반복생성하는 법
전에도 언급했듯, JSX내에선 for반복문을 못쓰기 때문에 map함수를 쓴다. (if문도 못써서 삼항연산자를 쓴다. )
나는 for문이 좋은데... 맵함수에 익숙해져볼게.....
array자리가 남고 div가 세개 생성. 리액트는 array안에 html을 담아놔도 잘 보여준다.
이렇게하면 이제 <div>가 3번 반복 된다! [1,2,3]의 요소가 세개니까.
근데 원하는 수만큼 반복할 때 마다 [1,2,3,4,,,] 이렇게 늘려야하나?
아니?
실제 블로그 글 갯수만큼 html을 생성하는거니까,
글제목도 원래 array였지! 글제목을 배열 자리에 넣자. 그럼 알아서 글제목배열의 length만큼 반복해줄테니까
각자 순서에 맞는 글 제목을 어떻게 넣어주나면,
a라는 파라미터는 map이 반복될 때마다 array자료 안에 있던 하나하나의 데이터를 의미한다.
그래서 a를 출력해보면 반복문이 돌 때마다 차례로 글제목의 내부 데이터 하나하나를 가져와서 ‘남자코트추천’ ‘강남우동맛집’이렇게 보여줌.
근데! map함수부분의 2번에 언급했듯이, function파라미터를 두개까지 작명 가능.
function (a, i)
i의 자리는
반복문이 돌 때 마다 0부터 1씩 증가하는 정수 (인덱스)
그래서 {글제목[i]} 랑 {a}랑 똑같은 결과가 나온다.
다시 정리,
map함수는
- array자료만큼의 인덱스만큼 내부코드를 실행시켜줌
- Return 이후 내용을 array로 담아줌
- 유용한 파라미터 2개 사용 가능 a, i
과제.......
엇 이거 좀 킹받는데요 💢
🔆과제 해결
useState를 이용할 때 초기값을 배열로도 넣을 수 있다는걸 알게되었다.
이렇게….
let[따봉,따봉변경]=useState([0,0,0])
여기서 따봉이라는 이름에 [0,0,0]의 배열을 줬고
곧 '따봉변경'이라는 state변경함수를 이용할거다.
<span onClick={()=>{ let copy = […따봉]; copy [i] = copy [i]+1; 따봉변경(copy); }}> 👍 </span> {따봉[i]}
따봉변경 함수를 이용해 따봉배열의 내부값에서 클릭할 때마다 1씩 증가하는 배열로 변경한다.
Props
Props의 특징으로는,
다른 함수끼리 변수 주고받을 수 없음 ('글제목'이 define되어있는 해당함수의 바깥에서는 ‘글제목’ is not defined라고 에러뜸.)
부모에서 자식방향으로만 가능함.
자식->자식 옆집끼리도 주고받기 불가능
부모컴포넌트에서 자식 컴포넌트로 state전송하는법
1. <자식컴포넌트 작명={state 이름}>
2. props 파라미터 등록 후 props.작명 사용
보통은 '작명'위치에 새로 이름짓기 귀찮으니까 state명이랑 똑같이 '글제목'이렇게 넣는다.
글제목={글제목}
이렇게.
하지만 나는 똑같이하면 되려 헷갈리더라..
부모->자식 state 전송하려면 props문법을 이용하는데,
1. 원래 넣으려던 고 자리에다가 <자식컴포넌트네임 새로지은이름={state이름}/>
2. 자식컴포넌트 function쪽에 props라고 파라미터 ()소괄호에 넣고 return쪽에 props.'새로지은이름' 으로 갖다 씀.
function Modal쪽에
props.color 로 밑작업해주고
</div> {modal == true ? <Modal color={'skyblue'} 작명={글제목} /> : null} </div>
HTML쪽에는 이렇게 컬러의 값을 준다
스타일을 이렇게도 줄 수가 있구나!
728x90'Java Script & Type Script' 카테고리의 다른 글
19. [리액트] 리액트 리덕스를 활용한 todo List 과제 진행상황 (0) 2023.01.04 18. React [리액트 숙련 주차] REDUX 리덕스를 쓰는 이유, Reducer, Dispatch, Action객체 용어 정리, 흐름의 이해 (0) 2023.01.02 15. React [리액트 애플코딩] 컴포넌트생성, 동적인 UI만들기 (0) 2022.12.29 14. React [리액트 애플코딩] JSX문법 , state, state변경함수 (0) 2022.12.28 13. React [리액트 스파르타 입문 강의] State- part 1 (0) 2022.12.26