티스토리 뷰
Array.prototype.map() 란?
map은 배열 내의 모든 요소 각각에 대하여 제공된 함수를 호출하고, 그 결과를 모아서 새로운 배열을 반환하는 메소드입니다. 우리가 가져온 프로필 정보를 map 메소드를 통해서 <Profile /> 컴포넌트에 다 전달해보도록 하겠습니다.
map 메소드의 매개변수
map 메소드는 현재 값, 인덱스(현재 처리되는 요소의 배열 내 인덱스), 본래 배열의 순서로 매개변수 값을 가집니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const nums = [1, 2, 3, 4, 5]; | |
const mapArr = arr.map((num, index) => num*index ); | |
// mapArr은 [0, 2, 6, 12, 20] 라는 배열을 가짐 |
위의 예시를 보면 nums라는 배열에 1~5까지의 숫자가 들어있고, map을 통해서 인덱스를 곱한 새로운 배열을 만들어 냈습니다. 인덱스는 0부터 시작하니 [0, 2, 6, 12, 20]이라는 배열을 가지게 됩니다.
renderProfile 함수 만들기
map 메소드를 통해서 우리가 가져온 프로필들을 전달 받은 <Profile /> 컴포넌트들을 반환하는 renderProfile함수를 만들어 보겠습니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class App extends Component { | |
//나머지 부분은 같습니다. | |
render() { | |
const { profiles } = this.state; | |
return ( | |
<div className="App"> | |
{profiles ? this._renderProfile() : "nothing"} | |
</div> | |
); | |
} | |
_renderProfile = () => { | |
const { profiles } = this.state; | |
const renderProfiles = profiles.map((profile, index) => { | |
return ( | |
<Profile | |
imgSrc={profile.picture.large} | |
name={profile.name.first} | |
username={profile.login.username} | |
password={profile.login.password} | |
key={index} | |
/> | |
) | |
}) | |
return renderProfiles; | |
} | |
} |
renderProfile 함수에서는 state에 있는 프로필 정보들을 가져와서 map을 활용해 <Profile />컴포넌트에 전달합니다. 이때 index를 key에 전달했습니다. 리액트에서는 이런식으로 이터레이트 할때 키라는 속성값이 필요합니다.
키 값을 전달하지 않으면 Warning: Each child in array or iterator should have a unique "key" prop 라는 경고 문구가 나타납니다.
프로필이 에러없이 나오는 것을 확인할 수 있습니다.
프로필의 경우 랜덤으로 오기 때문에 저랑 보이는 화면은 다르시겠지만 에러없이 나오고 있다면 잘 진행되고 있는 것입니다. 이제는 컴포넌트까지 다 잘 나오기 때문에 가져온 것들을 꾸미기만 하면됩니다. 반응형으로 제작해야 하니 flex에 대한 것을 모르시면 css부분에 있는 flex를 참고해주세요.
다음 포스팅에서는 css 작업을 해보도록 하겠습니다.
'Frontend-dev > react' 카테고리의 다른 글
리액트 앱 깃허브 페이지에 올리기 (1) | 2018.09.12 |
---|---|
css 작업하기 (0) | 2018.09.10 |
리액트 컴포넌트에 데이터 넣기 (0) | 2018.09.07 |
리액트에 데이터 불러오기 (0) | 2018.09.06 |
자식 컴포넌트 만들기 (0) | 2018.09.06 |
댓글