UI 구성에 필요하지만, B/E API가 준비되지 않았을 때, 프론트엔드 개발자가 필요에 의해 샘플로 데이터로 만들어 UI를 미리 개발할 수 있다.
Mock data는 백엔드 API를 모방하기에 실제 백엔드 API에서 응답값의 형태인 json 파일로 만들어줘야 한다.
JSON(JavaScript Object Notation) 데이터를 주고 받는 형식으로 사용 가능한 타입은 아래와 같다.
"
쌍따옴표만 유효하다.{
"name": "vi2920"
}
stringify()
- 자바스크립트 객체를 JSON 문자열로 직렬화 한다.parse()
- JSON을 파싱하여 자바스크립트 값으로 바꾼다.// Comment Data
[
{
"id": 1,
"userName": "wecode",
"content": "Welcome to world best coding bootcamp!",
"profile":"https://i.postimg.cc/SKknbzzV/wecode.png",
"isLiked": true
},
{
"id": 2,
"userName": "joonsikyang",
"content": "Hi there.",
"profile":"https://i.postimg.cc/9FrDnzk4/image.png",
"isLiked": false
},
{
"id": 3,
"userName": "jayPark",
"content": "Hey.",
"profile":"https://i.postimg.cc/SKknbzzV/wecode.png",
"isLiked": false
}
]
데이터를 요청하는 시점을 컴포넌트가 생성(Mount)된 이후에componentDidMount()
에서 fetch()
함수를 사용하여 데이터를 받고, 응답 받은 데이터는 setState()
함수를 사용하여 담아주면 된다.
// CommentList
import React, { Component } from 'react';
import Comment from '../Comment/Comment';
import './CommentList.scss';
class CommentList extends Component {
constructor(props) {
super(props);
this.state = {
commentList: [],
};
}
componentDidMount() {
fetch('http://localhost:3500/data/commentData_songhyun.json', {
method: 'GET',
})
.then(res => res.json())
.then(comments =>
this.setState({
commentList: comments,
})
);
}
render() {
const { commentList } = this.state;
return (
<ul className="feeds-comment__list">
{commentList.map(comment => {
return (
<Comment
key={comment.id}
name={comment.userName}
profile={comment.profile}
content={comment.content}
/>
);
})}
</ul>
);
}
}
export default CommentList;
// Comment.js
import React, { Component } from 'react';
class Comment extends Component {
render() {
const { profile, content, name } = this.props;
return (
<li className="feeds-comment__reply">
<div className="user-feeds__profile--img">
<img src={profile} alt="피드사진" />
</div>
<b className="user-feeds__name--others">{name}</b>
<p>{content}</p>
<i className="far fa-heart icon"></i>
</li>
);
}
}
export default Comment;