Array.map()
함수의 조합을 이용해서 간결하게 표현할 수 있습니다.commentData.json
[
{
"id": 1,
"userName": "wecode",
"content": "Welcome to world best coding bootcamp!",
"isLiked": true
},
{
"id": 2,
"userName": "joonsikyang",
"content": "Hi there.",
"isLiked": false
},
{
"id": 3,
"userName": "jayPark",
"content": "Hey.",
"isLiked": false
}
]
mock data는 백엔드 API를 모방하기에 실제 백엔드 API에서 응답값의 형태인 json
파일로 만들어줘야합니다.
http://localhost:3000/data/commentData.json
를 API 주소로 생각하고 http 요청을 통해서 API 요청을 보내고 응답을 받아보겠습니다.
commentList.js
import React, { useState, useEffect } from 'react';
import Comment from './Comment/Comment';
import './CommentList.scss';
function CommentList() {
const [commentList, setCommentList] = useState([]);
useEffect(() => {
fetch('http://localhost:3000/data/commentData.json', {
method: 'GET' // GET method는 기본값이라서 생략이 가능합니다.
}) // 예시코드에서는 이해를 돕기 위해 명시적으로 기입해뒀습니다.
.then(res => res.json())
.then(data => {
setCommentList(data);
});
},[])
return (
<div className="commentList">
<h1>Main Page</h1>
<ul>
{commentList.map(comment => {
return (
<Comment
key={comment.id}
name={comment.userName}
comment={comment.content}
/>
);
})}
</ul>
</div>
);
}
export default CommentList;
fetch
함수를 사용합니다.fetch
함수는 첫번째 인자로 http 요청을 보낼 API주소, 두번째 인자로 요청을 보낼때의 옵션들을 객체형태로 받습니다.GET
method를 활용해 요청을 보냈습니다.setCommenList
함수를 사용하여 commentList
state를 응답 받은 값으로 바꿔줍니다.