Westagram code review

Yunji·2020년 5월 23일
0

TIL

목록 보기
53/54
post-thumbnail

서버에서 불러온 댓글 map 돌리는 함수
componentDidMount 에서 불러온 데이터를 setState 로 저장해서 그 데이터를 Map으로 돌리는 코드인데 자꾸 map에서 에러가 났다 확인해보니 props 로 전달되는 값이 없었다 그래서 다시 살펴보니 Lifecycle 순서의 문제였다 그래서 props 로 전달되는 값이 없으면 map이 실행되지 않게 조건을 달아서 해결했다

// Article.js
// main 화면 업데이트 할 떄 기존 댓글 불러오기
    componentDidMount() {
        fetch("http://10.58.0.163:8000/feed/comment", {
            method: "GET",
            headers: {
                // 해당 사용자 구별을 위해 로컬 스토리지에 저장되어 있는 토큰 보내기
                Authorization: localStorage.getItem("access_token")
            }
        })
        	// .json() = JSON -> JS
 			// JSON.stringify() = JS -> JSON
      		// 응답 받은 json 데이터를 javascript 로 변환
            .then(res => res.json())
      		// 변환한 데이터 setState 로 저장
            .then(res => this.setState({
                res_comments : res
            }))
    }  
// CommentList 컴포넌트에 데이터 props 로 전달
<CommentList_yj commentswrap={this.state.res_comments["comments"]} />
// CommentList.js 
// commentList.js 컴포넌트 생성
class CommentList_yj extends React.Component {
    render() {
      	// commentwrap(CommentList 에서 받아온 props) 비구조화 할당 
        const { commentswrap } = this.props;
        console.log(this.props)
        // (commentswrap &&) 로 조건 달아주어 에러 안나게 하기
        // 조건 : props 가 비어있으면 map 이 실행되지 않음
        const commentList = commentswrap && commentswrap.map((post, idx) => (
     			// Commnet 컴포넌트에 댓글내용과 사용자이름 props 로 전달하기
                <Comment_yj key={idx} text={post.content} userI={post.username} />
            )
        );
        return(
            <div>
                {commentList}
            </div>
        );
    }
}

밑에 코드는 댓글을 작성해서 서버로 그 데이터를 보내는 코드인데 보내고 나서 get으로 다시 정보를 받아와야 한다 일단 post 로 보내는 코드만 구현해놨다

// Article.js
// 댓글 입력시 데이터를 서버로 전달하는 함수
handleCreate = () => {
  		// 로컬 스토리지에 저장되어있는 토큰을 변수에 담기
        const token = localStorage.getItem("access_token");
        fetch('http://10.58.0.163:8000/feed/comment', {
          	// post 로 전달
            method: "POST",
            headers: {
              'Content-Type': 'application/json',  
              Authorization: token  
            },
          	// body 에 댓글 내용 전달
            body: JSON.stringify({
                text: this.state.input,
                feed_id: 3
            })
        })                                                                         
    }

0개의 댓글