React Router Dom / Flow& Axios / CORS이슈 & Proxy 설정 / Concurrently / Redux 기초 / #20~#26

해버니·2022년 8월 2일
0

노드 & 리액트

목록 보기
6/9
post-thumbnail

React Router Dom

리액트에서는 페이지 간 이동을 할 때 "react router dom" 이라는 것을 쓴다.

https://reactrouter.com/docs/en/v6/upgrading/v5



import {
BrowserRouter,
Route,
Routes,
//Link
} from "react-router-dom";

import LandingPage from './components/views/LandingPage/LandingPage'
import LoginPage from './components/views/LoginPage/LoginPage'
import RegisterPage from './components/views/RegisterPage/RegisterPage'

function App() {
return (
<BrowserRouter>
<Routes>

<Route exact path="/" element = {<LandingPage/>}/>
<Route exact path="/login" element = {<LoginPage/>}/>
<Route exact path="/register" element = {<RegisterPage/>}/>

</Routes>

</BrowserRouter>
);

}

수업기준 v.5 -> Router node v.6 으로 바뀌었기 때문에 위와 같이 코드를 작성해야 한다.







로그인 페이지, 랜딩 페이지 다 잘 돌아간다 호홍





Flow & Axios

지금까지 수업에서는 Client 부분이 없었기 때문에 POSTMAN (VS code thunder Client) 을 이용해서 했다.
하지만 이제는 Client를 만들었으니 React JS 부분에서 Request를 보내면 되는데 그때 사용하게 될 것이 AXIOS이다.
(jQuery를 사용할 때 AJAX라고 보면 된다.)

npm install axios --save

터미널에서 다운 받기 !




문제..

모듈이 찾아지지 않는다.

하지만 나는 해냈찌



해결 완료
package.json 파일 내에서 main 부분을 바꿔줘야한다.
왜냐하면 server & client 폴더를 나눠서 옮겨놨기 때문에!

(server 파일을 옮겨놓았는데 고걸 index.js 에 적용시키지 않았다. ㅠㅠ
그래도 해결돼서 다행이야)





CORS 이슈 & Proxy 설정










클라이언트에서

npm install http-proxy-middleware --save

다운 받기




문제

해서 다시 클라이언트, 백엔드 npm run start 했는데 왜 이렇게 뜨지? 힝

http-proxy-middleware가 버전업이 되서 쓰는 법이 바뀌었다

수업은 위 코드로 진행을 하였는데
밑 코드로 바꿔서 진행을 해야한다!


const proxy = require('http-proxy-middleware');

module.exports = function(app) {
	app.use(
		'/api',
		proxy({
			target: 'http://localhost:5000',
			changeOrigin: true,
		})
	);
};



const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function (app) {
    app.use(
        '/api',
        createProxyMiddleware({
            target: 'http://localhost:5000',
            changeOrigin: true,
        })
    );
};


콘솔도 정상적으로 뜬다.
반갑습니다람쥐~






Proxy Server

프록시가 무엇일까?



사용 이유

  1. 회사에서 직원들이나 집 안에서 아이들 인터넷 사용 제어
  2. 캐쉬를 이용해 더 빠른 인터넷 이용 제공
  3. 더 나은 보안 제공
  4. 이용 제한된 사이트 접근 가능






Concurrently

npm install concurrently --save

다운받기


npm run dev 하면 백엔드, 프론트 둘 다 킬 필요없이 한 번만 실행하면 된다.

연결이 잘된걸 볼 수 있다.





Antd CSS Framwork

우리는 CSS Framework를 쓸건데 쓰는 이유는?
기능을 만드는데 더욱 집중하기 위해서!

실무에서도 요즘엔 프레임워크 + Styled component를 이용해서 많이 쓰고 있다.


여러가지가 있는데 우리 수업에서 쓸것은 Ant Design을 쓸 것이다.

단점 : 사이즈가 큼
장점 : 스타일이 너무 깔끔 & 사용하기 굉장히 편함



npm install antd --save

다운 받기



그리고 client 부분 index.js에 import 'antd/dist/antd.css';
추가해주기

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

import 'antd/dist/antd.css';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();






Redux 기초

Redux가 뭐야?

Redux is a predictable state container
상태 관리 라이브러리이다.


근데 state?가 어떤거지?

리액트에서는 주요하게 PropsState 가 있다.


Props

우리가 흔히 알고있는 property의 줄임말이다.
컴포넌트간에 무언가를 주고받을 때는 Props을 이용해야 한다.
이용하는 방식은 부모에서 자식으로만 보낼 수 있다.
만약 부모 컴포넌트에서 자식 컴포넌트로 1을 보낸다면 자식 컴포넌트의 value는 변할 수 없다.
바뀌려면 다시 부모 컴포넌트에서 자식 컴포넌트에게 다른 value를 내려야 한다.


1. shorthand for properties
2. Props are how components talk to each other
3. Props flow downwards from the parent component
4. Props are immutable from the child perspective if you want to change that value? the parent should just change its internal state



State

부모 컴포넌트에서 자식 컴포넌트에게 주는게 아니라 컴포넌트 내에서 데이터를 교환, 전달을 하려면 그때 state를 써야한다.
부모 -> 자식으로 value를 내려줄 필요 없이 그저 변경할 수 있다.


1. parent component에서 child component로 data를 보내는 게 아닌 그 컴포넌트 안에서 데이터를 전달하려면? state로
예를 들어서 검색 창에 글을 입력할 때 글이 변하는 것은 state을 바꾸는 것이다.
2. State is mutable
3. state이 변하면 re-render 된다.



그래서 Redux는

이런 state를 관리하는 것이라고 생각하면 된다.


Action은 객체인데 무엇이 일어났는지 설명하는 객체이다.

Reducer는 "액션을 함으로인해서 state가 3->4로 변했다" 라고 설명해주는 곳

Store는 전체적인 어플리케이션의 state을 감싸주는 역할을 하고 있고
그 안에는 많은 메소드들이 있다
그걸 이용해서 state를 관리를 할 수 있다.


0개의 댓글