본문 바로가기

Project 기록/컴공 커뮤니티(web)

게시판만들기 db에 저장된 데이터를 목록으로 보여주자(react,mysql)

반응형

 

 

 

 

 

↓ 지난 번에 미리 초기화한 객체배열을 리스트로 보여줬다 꼭 보시길 ㅜㅜ 

 

coding-hwije.tistory.com/56

 

게시판만들기 데이터를 목록으로 보여주자(react,list,map)

만들고 잇는 게시판 게시물인데 밋밋하다 댓글 리스트를 보여주고 싶다 먼저 데이터 리스트가 필요하다 바로 반응하기 위해서 난 state값으로 list이름의 배열을 만들어 줫다 class Boardreple extends Co

coding-hwije.tistory.com

 

 

 

 

저번 게시물에 만든 목록인데 미리 초기화가 아니라 

 

디비에서 가져오고 싶다

 

 

 

 

 

 

먼저 데이터 리스트가 필요하다

class Boardreple extends Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [], // <== 비어잇음
    };
  }

 

 

 

 

 

객체를 반환하는 함수

function createData(number, nick, time, reple, recomend) {
  return { number, nick, time, reple, recomend };
}

number, nick , time, reple ,recomend를 받아서 객체로 만들고 반환한다.

 

 

 

 

 

 

 

 

디비에서 데이터 가져오기 -> 그걸로 list 초기화 -> 렌더 

 

순으로 갈거다

 

 

 

 

 

 

이건 댓글 데이터베이스 칼럼들

 

 

 

데이터를 가져올때 fetch함수다

fetch("http://localhost:3001/repDownload", {
                method: "post",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(data),
              })
                .then((res) => res.json())
                .then((json) => {
                  if (json === undefined) {
                    alert("오류");
                  } else {
                  //////////////////////////////////          여기부터보자
                    for (let i = 0; i < json.length; i++) { //가져온 json파일을 길이만큼 돌린다
                      this.setState({                       //list가 sate값이기 때문에 setState
                        list: this.state.list.concat(       //배열을 '이어 붙이'는것이기 때문에 concat사용
                          createData(                       //객체 만들기
                            json[i].number,
                            json[i].nick,
                            json[i].time,
                            json[i].reple,
                            json[i].recomend
                          )
                        ),
                      });
                    }
                  //////////////////////////////////
                    console.log(json);
                  }
                });

 

가져온 json파일 길이만큼 돌림-> i번째의 데이터들로 createDate(..) -> 기존 list에 concat

 

 

 

 

 

 

랜더 이후의 코드

render() {

    const content = this.state.list.map((list) => ( // 리스트를 하나씩 살펴본다
    //이제 표현 하고싶은데로 하면 됨
      <div key={list.number}> //현재 객체의 number
        <div >
          <div >
            <div >{list.nick}</div> //현재 객체의 nick
            <div > {list.time}</div> //현재 객체의 time
          </div>
          <div >
            <img src={like} width="12" height="12" className="rep_rexobtn" /> 
            <div>
              좋아요: {list.recomend} //현재 객체의 recomend
            </div>
          </div>
        </div>
        <div>{list.reple}</div> //현재 객체의 reple
      </div>
      
    ));

    return <div>{content}</div>;  //여기서 content 출력
  }

 

 

 

 

 

 

아 그리고 

fetch랑 연결되는 server는 이렇게 썼음

app.post("/repDownload", (req, res) => {
  let sql = "SELECT * FROM reple_ ";

  connection.query(sql, function (err, rows, result) {
    //연결!
    if (err) throw err;
    else {
      // console.log(rows);
      // console.log(result);
      res.send(rows);
    }
  });
});

 

 

 

 

 

 

 

 

 

 

 

반응형