Fullstack-Study-241204-250625

커리큘럼(12-30/변경)

01. Java
02. git
03. Database 
04. Jsp [Server]

05. HTML,CSS 
07. JS
06. 미니프로젝트-2W

08. SpringFramework , SrpingBoot 
19. 중간프로젝트 (1M)
10. Linux 명령어
11. AWS
12. Docker
13. Kubernetes
14. React JS (v)
15. App - Android
16. 최종프로젝트 (1M)

React(리액트)

React 라우터

URL파라미터 / 쿼리스트링

  1. 쿼리스트링

<Link to="/user?id=aaa123&addr=서울시">유저화면</Link>

const location = useLocation();

  • 객체형태로 반환

const [param,setParam] = useSearchParams();

  • 배열을 반환
  • 첫번째 요소는 쿼리파라미터를 조회하거나 수정하는 get,set이 담긴 객체로 get요소를 통해 파라미터를 얻을 수 있음

const id = param.get("id");

  • 두번째 요소는 쿼리파라미터를 객체로 업데이트 하는 함수 반환
  1. URL파라미터
function App() {

  return (
    <Routes>
        .....
        <Route path='/info/:num' element={<Info/>}/>
    </Routes>
  );
}

<li><Link to='/info/1'>1번 info</Link></li>

const params = useParams();
const age = params.age;
  • useParams()를 사용해서 넘어온 값을 받을수있음

중첩라우터로 공통부분 처리

<Route path='/board' element={<Board/>}/>
<Route path='/board/:bno' element={<BoardContent/>}/>
/* App.js */
<Route path='/board' element={<Board/>}>
    <Route path=':bno' element={<BoardContent/>}/>
</Route>

/* Board.js */
<ul>
    <li><Link to='/board/1'>첫번째 글</Link></li>
    <li><Link to='/board/2'>두번째 글</Link></li>
    <li><Link to='/board/3'>세번째 글</Link></li>
</ul>

<Outlet/>
  • 라우팅 경로를 설정해주는 App.js에서 중첩 라우팅을 써서 경로 설정
  • 상위 라우팅주소에서는 하위 라우팅 주소의 화면을 쓸곳을 **Outlet태그**를 이용하여 설정

라우터의 부가적인 기능

  1. NavLink 컴포넌트
function Board(){


    const myStyle = {
        color:'red',
        backgroundColor:'green'
    }
    return(
        <>

            <h3>글화면</h3>


            <ul>
                {/* <li><Link to='/board/1'>첫번째 글</Link></li>
                <li><Link to='/board/2'>두번째 글</Link></li>
                <li><Link to='/board/3'>세번째 글</Link></li> */}

                {/* NavLink는 url주소가 선택한 링크와 같을때 style을 줄수 있음 */}
                <li><NavLink to='/board/1' style={({isActive})=>isActive ? myStyle : null}>첫번째 글</NavLink></li>
                <li><NavLink to='/board/2' style={({isActive})=>isActive ? myStyle : null}>두번째 글</NavLink></li>
                <li><NavLink to='/board/3' style={({isActive})=>isActive ? myStyle : null}>세번째 글</NavLink></li>
            </ul>

            <Outlet/>
        </>
    )
}
  1. useNavigate()훅

let navigator = useNavigate();

function Header(){

    // 뒤로가기, 앞으로가기, 특정라우터로 가기
    const nav = useNavigate()

    return(
        <>
            <header style=>
                <h3>공통으로 사용하는 헤더입니다</h3>
                <button type="button" onClick={()=>nav('/')}>홈</button>
                <button type="button" onClick={()=>nav('/user')}>유저</button>
                <button type="button" onClick={()=>nav(-1)}>뒤로가기</button>
            </header>


            <Outlet/>
        </>
    )
}
  1. Navigate 컴포넌트
function Mypage(){
    
    const loginYn = false; // 로그인x

    // 권한에 대한 검사
    // 첫 렌더링 과정에서 useNavigate는 사용하지 못함
    // const nav = useNavigate();
    // if(!loginYn){
    //     nav('/');
    // }

    // 렌더링 과정에 권한 검사를 통해 다른 페이지로 보냄
    if(!loginYn){
        return <Navigate to='/' replace={true}/>;
    }
    return(
        <>
            <h3>권한이 있는 사람만 들어올 수 있음</h3>
        </>
    )
}

Ajax(Asynchronous Jabascript and XML)

ES6의 fetch를 이용해 리액트에서 데이터 처리

  1. 이벤트 클릭시 처리
function App(){

    const [data,setData] = useState({
        userId:null,
        userName:null,
        userPw:null
    });

    const handleClick=()=>{
        fetch('https://raw.githubusercontent.com/yopy0817/data_example/master/hi.json')
        .then(response => response.json())
        .then(data=>{
            setData(data);
        })

    }
        
    return(
        <>
            <h3>Ajax통신</h3>

            <button type="button" onClick={handleClick}>1.버튼클릭시 ajax통신</button>   
            <br/>
            가져온데이터 {data.userId},{data.userName},{data.userPw}



            <br/>
            화면 로딩시에 가져온 데이터 {myData.userId}, {myData.userName},{myData.userPw}
        </>
    )
}
  1. 화면 렌더링 완료시 데이터 처리
function App(){

    const [data,setData] = useState({
        userId:null,
        userName:null,
        userPw:null
    });

    const handleClick=()=>{
        fetch('https://raw.githubusercontent.com/yopy0817/data_example/master/hi.json')
        .then(response => response.json())
        .then(data=>{
            setData(data);
        })

    }


    // 화면에 진입하자마자 데이터를 가져오는 방법
    const [myData,setMyData] = useState({userId: '' ,userName:'',userPw:''});
    useEffect(()=>{
        fetch('https://raw.githubusercontent.com/yopy0817/data_example/master/hi.json')
        .then(response => response.json())
        .then(data=>{
            setMyData(data);
        })
    },[])

    console.log(11);
    
    return(
        <>
            <h3>Ajax통신</h3>

            <button type="button" onClick={handleClick}>1.버튼클릭시 ajax통신</button>   
            <br/>
            가져온데이터 {data.userId},{data.userName},{data.userPw}



            <br/>
            화면 로딩시에 가져온 데이터 {myData.userId}, {myData.userName},{myData.userPw}
        </>
    )
}

Axios로 데이터 처리

npm install axios

Promise = axios.get(요청주소)

1. 이벤트 클릭시 처리

function App(){
    // npm install axios

    const handleClick = ()=>{
        axios.get('https://raw.githubusercontent.com/yopy0817/data_example/master/hi.json')
        .then( response => {
            console.log(response.data.userId);
        })
    }
    return(
        <>
            <h3>엑시오스 사용</h3>
            <button type = "button" onClick={handleClick}>데이터 처리</button>
        </>
    )
}
  • axios의 get함수안에는 주소를 넣음
  • axios의 post함수의 경우 첫번째 매개변수에는 주소, 두번째 매개변수에는 데이터를 넣음

axios.post(url, data, config);

  • axios는 서버에서 받은 응답을 자동으로 JSON 파싱해주기 떄문에 객체형태로 받은 데이터를 바로 쓰면됨

2. async(비동기) , await(대기) 적용

  1. 어싱크 함수 안에서 어웨잇 사용
  2. **function앞에 async키워드를 추가**하고 함수는 언제나 프로미스를 반환
  3. 리턴이 프로미스라면 await을 적용하고 then절을 없앨 수 있음
axios.get('https://raw.githubusercontent.com/yopy0817/data_example/master/hi.json')
.then( response => {
    console.log(response.data);
    console.log(1);
})

axios.get('https://raw.githubusercontent.com/yopy0817/data_example/master/hi.json')
.then( response => {
    console.log(response.data);
    console.log(2);
})

axios.get('https://raw.githubusercontent.com/yopy0817/data_example/master/hi.json')
.then( response => {
    console.log(response.data);
    console.log(3);
})
axios.get('https://raw.githubusercontent.com/yopy0817/data_example/master/hi.json')
.then( response => {
    console.log(response.data);
    console.log(1);

    axios.get('https://raw.githubusercontent.com/yopy0817/data_example/master/hi.json')
    .then( response => {
        console.log(response.data);
        console.log(2);

        axios.get('https://raw.githubusercontent.com/yopy0817/data_example/master/hi.json')
        .then( response => {
            console.log(response.data);
            console.log(3);
        })
    })
})
const handleClick = async()=>{
    // 규칙1 - await키워드는 async 함수 안에서 사용할 수 있음
    // 규칙3 - 리턴이 프로미스라면 await를 붙이고 then을 생략가능
    // 장점 - 코드의 간결성
    // 장점 - 동기적으로 변하게 됨
    const response = await axios.get('https://raw.githubusercontent.com/yopy0817/data_example/master/hi.json')
    console.log(response);
    const response2 = await axios.get('https://raw.githubusercontent.com/yopy0817/data_example/master/hello.json')
    console.log(response2);
    
    
    const response3 = await axios.get('https://raw.githubusercontent.com/yopy0817/data_example/master/by.json')
    console.log(response3);
    
}
  • **async함수**는 Promise를 반환
  • **Promise**는 비동기 작업의 완료(또는 실패)를 처리하는 객체
  • **await함수**는 반드시 async함수 안에서만 쓸수 있으며 async함수는 해당 요청이 완료될때까지 대기했다가 완료되면 다음 요청을 이어서 실행시킴
  • 비동기적인 흐름을 동기흐름처럼 바꿔줌
  • axios는 Promise를 반환하고, then으로 결과를 처리하는데 axios앞에 await을 사용하면 then을 생략가능하고 바로 결과를 변수에 받을 수 있음
useEffect(() => {
    
    (async () => {
        let url = '주소';
        let response = await axios.get(url);
				//state업데이트
    })();


}, []);