Mock Data와 componentDidMount() 메서드, fetch함수에 대해서 적어보자
fetch
함수가 익숙지 않은 분들은 .json
파일이 아닌 .js
파일로 데이터를 관리해주세요..json
파일로 변환 후 fetch
함수 적용해서 구현해주세요.✨ mock data로 사용될 json 파일을 관리하는 방법
public 폴더 > data 폴더 > commentData.json
✨ commentData.json
[
{
"id": 1,
"userName": "jyb_1111",
"talks": "예쁘네요"
},
{
"id": 2,
"userName": "jdh_2222",
"talks": "멋집니다"
},
{
"id": 3,
"userName": "kws_3333",
"talks": "WoW!!!"
}
]
✨ 연결 : componentDidMount() 메서드와 fetch함수
componentDidMount() 메서드 :
componentDidMount() : "최초에 한번만 작동하라"는 기능의 메서드. componentDidMount()는 component 안에서 한 번만 사용 가능하다.
fetch함수
class Feeds extends Component {
constructor() {
super();
this.state = {
newComment: '',
comments: [],
commentList: [],
feedList: [],
};
}
}
componentDidMount() {
fetch('http://localhost:3000/data/younbeejee/commentData.json')
.then(res => res.json())
.then(res => {
console.log(res);
this.setState({
commentList: res,
});
console.log(this.state.commentList);
});
}
render() {
return (
<div className="feeds">
<article className="container">
<div className="line">
<img
className="me"
alt="me_01"
src="https://media.istockphoto.com/photos/beautiful-woman-with-colors-smeared-on-her-face-picture-id1277619606?s=612x612"
/>
<span className="text1">
<b>jyb0924</b>
</span>
</div>
<div className="photo">
<img className="main_img" alt="main_image" src="https://media.istockphoto.com/photos/woman-standing-on-the-stairs-picture-id873375304?k=20&m=873375304&s=612x612&w=0&h=RxgCX3B5F1YyKj3usV6oDD8NsIUBX7XBLvAi3AGKSvE=" />
</div>
</div>
</div>
<div className="heart_line">
<img className="heart_lne" alt="33dung" src={el.feedsPhoto} />
<div className="text2">33dung님 외 100명이 좋아합니다</div>
</div>
<div className="many_lines">
<ul className="items">
<Child commentList={this.state.commentList} />
{this.state.comments.map(el => (
<li className="item">
<span className="itemText">{USER_NAME}</span>
{el.text}
</li>
))}
</ul>
</div>
<hr />
<div className="comment">
<input
className="input"
type="text"
placeholder="댓글 달기..."
onChange={this.textChange}
onKeyPress={this.pressEnter}
value={this.state.newComment}
/>
<button className="itemAdd" onClick={this.add}>
<a href="javascript:void(0)">게시</a>
</button>
</div>
</article>
</div>
);
}
}
export default Feeds;
const USER_NAME = 'jyb0924 ';