[Westagram] 003. Main comment

홍효정·2020년 10월 17일
0

TIL

목록 보기
17/40

Main

Main 컴포넌트

▪ state

constructor() {
  super();
  this.state = {
    name: "",
    id: 3,
    commentInput: "",
    commentData: [
      { 
        id: 0, 
        userId: "홍효정", 
        comment: "집에 가고싶어요", 
        like: false 
      },
      { 
        id: 1, 
        userId: "wecode_bootcamp", 
        comment: "화이팅", 
        like: true 
      },
      { 
        id: 2, 
        userId: "홍효정", 
        comment: "ㅠㅠ", 
        like: false 
      },
    ],
  };
}

main feed 댓글의 state 초기값을 정의한다.


▪ methods

handleCommentChange
handleCommentChange = (e) => {
  this.setState({
    commentInput: e.target.value,
  });
};

댓글 input에 값이 들어오면 해당input의 value값을 commentInput에 저장한다.


handleCommentCreate
handleCommentCreate = () => {
  const { commentData, commentInput } = this.state;
  if (commentInput.length > 0) {
    this.setState({
      commentData: commentData.concat({
        id: this.state.id,
        userId: "홍효정",
        comment: commentInput,
        like: false,
      }),
      id: this.state.id + 1,
      commentInput: "",
    });
  }
};

댓글 생성 함수. 현재 state중 commentData와 commentInput을 받아와서 input에 값이 있을때 함수 실행시 concat메서드로 새로운 댓글 컴포넌트를 만든다.


handleCommentClickAdd, handleCommentKeypressAdd
handleCommentClickAdd = () => {
  this.handleCommentCreate();
};

handleCommentKeypressAdd = (e) => {
  if (e.key === "Enter") {
    this.handleCommentCreate();
  }
};

게시 버튼을 클릭하거나 키보드 enter를 치면 댓글 생성 함수를 실행한다.


handleCommentLike
handleCommentLike = (id) => {
  const { commentData } = this.state;
  const index = commentData.findIndex(
    (commentData) => commentData.id === id
  );
  const selected = commentData[index];
  const nextCommentData = [...commentData]; // spread syntax

  nextCommentData[index] = {
    ...selected,
    like: !selected.like,
  };
  
  this.setState({
    commentData: nextCommentData,
  });
};

배열의 값을 직접 수정하지 않고 spread syntax(전개연산자)를 활용했었던 좋아요 기능. 클릭한 댓글의 인자로 받아온 id와 commentData배열안의 idfindIndex메서드로 찾아와서 일치하면 그 index인 배열의 state like를 true, false로 전환한후 setState한다.


handleCommentDelete
handleCommentDelete = (id) => {
  const { commentData } = this.state;
  this.setState({
    commentData: commentData.filter(
      (commentData) => commentData.id !== id
    ),
  });
};

클릭한 댓글의 id를 갖고있지 않는 배열을 filter메서드로 생성하여 commentData로 setState한다.

profile
HHJ velog 🍔

0개의 댓글