React 배열 사용하기

13182 단어 ReactemotionDiaryReact

리스트 렌더링 조회

결과물

다음과 같이 리스트를 렌더링하여 App.js 로 불러온다.

App.js

const dummyList = [
  {
    id: 1,
    author: "이름",
    content: "hellow?",
    emotion: 5,
    created_date: new Date().getTime(),
  },
  {
    id: 2,
    author: "이름2",
    content: "hellow!",
    emotion: 3,
    created_date: new Date().getTime(),
  },
  {
    id: 3,
    author: "이름3",
    content: "hellow+",
    emotion: 4,
    created_date: new Date().getTime(),
  },
  
];
  • 다음과 같이 dummyList를 만들고 요소들은 객체로 만든다.
  • new Date().getTime()를 이용하면 현제시간을 가져올 수 있다.

    그러나 new Date().getTime()만을 이용하면 위의 회색 글자와 같이 사람은 이해하기 어려운 숫자로 출력된다.(아래에서 보기좋은 날짜를 만드는 방법을 알아본다.)

이렇게 만들어진 dummyList를 다른 컴포넌트에서 가공하여 App컴포넌트에 뿌려준다.
가공하기 위한 컴포넌트를 DiaryList라고 이름붙인다.

function App() {
  return (
    <div>      
      <DiaryEditor />
      <DiaryList diaryList = {dummyList} />
    </div>
  );
};

export default App;

DiaryList에는 diaryList라는 이름으로 dummyList를 보내준다.


DiaryList

const DiaryList = ({ diaryList }) => {
	return (
    	<div className="DiaryList">
            <h2>일기 리스트</h2>
            <h4>{diaryList.length}개의 일기가 있습니다.</h4>
            <div>
                {diaryList.map((it) => (
                    <DiaryItem key = {it.id} {...it} />                    
                ))}
            </div>
        </div> 
    )
}

DiaryList.defaultProps = {
    diaryList: [],
};
// diaryList가 비었을때 default값을 정해주지 않으면 error가 발생한다.

export default DiaryList;

받아온 diaryList는 배열로서 받게된다.

  • 여기서의 id, author, content등의 요소들을 사용할 수 있다.
  • 이 요소들을 사용하기 위해서 diaryList를 map으로 묶어 사용한다.
  • 이때 DiaryItem이라는 컴포넌트를 만들어 id, author, content의 요소의 값들을 넘겨준다.
    {...it}을 사용하면 diaryList의 모든요소들을 펼쳐서 넘겨줄 수 있다. -> author, content, emotion등 펼쳐서 넘겨줌.

DiaryItem

const DiaryItem = ({author, content, created_date, emotion, id }) => {
    return (
        <div className='DiaryItem'>
            <div className='info'>
                <span>
                    작성자 : {author} | 감정점수 : {emotion}
                </span>
                <br />
                <span className='date'>{new Date(created_date).toLocaleString()}</span>
            </div>
            <div className='content'>{content}</div>    
        </div>
    );
};

export default DiaryItem; 
  • DiaryItem은 diaryList의 요소들을 사용할 수 있다.

  • new Date()에 아까는 읽을수없던(?) 날짜 데이터(created_date)를 넣어주고, toLocalString()을 써주면 현제 날짜 시간을 불러올 수 있다.


위와같이 데이터를 컴포넌트에 불러 가공한다음 가공한 데이터를 다시 상위 컴포넌트에 돌려준다.

좋은 웹페이지 즐겨찾기