반응형

저번에는 글쓰기를 알아보았다

CRUD를 진행하면서 리엑트는 좀 어려운거같다 

자바스크립트나 제이쿼리의 DOM 방식이 익숙해졌는데 

리엑트의 방식은 나에게 너무 크게 다가왔다.

 

오키 등 다른 곳에 질문을 올려서 꾸역꾸역 해가고 있다.

점점 성장하는거같다 기쁘다.

 

 

먼저 리엑트부분부터 살펴보자 

 

 <Routes>
      <Route path='/' element={
      <div>메인페이지
        <a href='/Write'>글쓰기</a>
        <h1>List</h1>
        <table>
        <tr>
          <th>번호</th>
          <th>제목</th>
        </tr>
      {
        list.map(function(a,i){
          return(
            <>
                <tr>
                  <td>{list[i].id}</td>
                  <td><Link to={`/detail/${list[i].id}`} onClick={
                    () => {
                      axios.get(`/board/detail/${list[i].id}`).then( res =>{   
                        Setboard(res.data)})
                  }
                  }>{list[i].title}</Link></td>
                </tr>
              </>
          )
        })
    }
    </table>
      </div>}>
        
      </Route>
      <Route path="/write" element={ <Write/> } />
      <Route path='/detail/:id' element={<Detail board={board}/> } />
    </Routes>
      
    </div>


  );
}

우선 테이블 태그로 리스트를 가볍게 그려주자 

그리고 link태그를 사용하여 list의 글번호를 가게하자 

즉 /detail/1 이런식으로 보내진다. 

 

그 다음 axios로 get요청을 보낸다. 

그 후 데이터베이스에서 받아온 내용을 res라는 함수에 저장하여 

Setboard에 저장한다. 

 

그 후 라우터를 통해 board를 props로 담아서 보내준다.

 

※ 주의사항 ※

 

나는 계속 res를 setboard에다 담고 console찍어 보면

계속 이전 값이 나온다 . 

 

그래서 해결책을 찾았다

 

State의 값 변경은 렌더링을 유발시키는 이유로 변경사항을 모아뒀다가 렌더링 주기마다 한번에 처리하기때문에 값이 바로 변경되지 않습니다.

값변경의 감지는 useEffect 훅을 사용하셔야합니다

 

useEffect(() => {
  console.log(board);
}, [board]);

을 추가하면 된다. 

 

다음으로 

 

디데일.js를 보자

 

import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";

function Detail(props){

    let {id} = useParams();


    return(
        <>
    <div>
        <input name='id' value={props.board.id}/>
    </div>
    <div>
        <input name='title' value={props.board.title}/>
    </div>
    <div>
        <textarea name='content' value={props.board.content}></textarea>
    </div>
        </>
    )
}

export default Detail;

 

그 후 props로 뿌려주면 끝난다. 

 

이제 스프링을 보자 

 

 

    @GetMapping("/board/detail/{id}")
    public Board detail(@PathVariable Integer id){
        return boardService.boardView(id);
    }

 

우선 간단하게 /{id}를 붙였으니

pathvariable로 해준다. 

 

그다음 서비스에서 받은 값을 리턴보내면 컨트롤러의 역활을 끝이다. 

 

서비스를 보면서 이해해보자 

 

    public Board boardView(Integer id){
        return boardRepository.findById(id).get();
    }

id를 보내서 id를 찾는다. 

 

https://github.com/MoonSeokHyun/Vegan-Recipe-WebSite

 

GitHub - MoonSeokHyun/Vegan-Recipe-WebSite

Contribute to MoonSeokHyun/Vegan-Recipe-WebSite development by creating an account on GitHub.

github.com

 

반응형

+ Recent posts