본문 바로가기
  • 기록
React/인프런

[(인프런)따라하며 배우는 노드 리액트 시리즈] 기본 강의

by juserh 2022. 4. 26.

#15 리액트란?

  • 컴포넌트
  • virtual DOM: 아이템 하나만 업데이트 가능. snapshot.   (cf. real DOM

#17

npm:

npx: disk space 낭비X, npm registery에서 다운로드 없이 가져와 실행해 항상 최신버전 사용 가능

 


#18

webpack: src폴더에 한해서만

이미지 넣을 때는 scr폴더에 넣어 webpack의 기능이 실행되도록 하자.


#19 CRA to Out Boilerplate


#20

react router dom: 페이지 간의 이동

https://v5.reactrouter.com/web/guides/quick-start

 

Declarative routing for React apps at any scale | React Router

Version 6 of React Router is here! React Router v6 takes the best features from v3, v5, and its sister project, Reach Router, in our smallest and most powerful package yet.

reactrouter.com

1.에러

export 'Switch' (imported as 'Switch') was not found in 'react-router-dom'

switch 버전6에서는 지원X. Switch->Routes로 바뀜. component도 element로 바뀜.


#21 데이터 Flow&Axios

  1. client -> server : request
  2. server <-> database
  3. server -> client : response

Axios: client에서 server로 request 보내기 위해 필요한 라이브러리


 

axios 실습 진행 시 에러 발생

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.

https://mr-son.tistory.com/153

 

React - BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default

React를 BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default error가 발생할 수 있다. webpack 버전이 5 이상이 되면서 더이상 지원하지 않는 것이기 때문에 webpack..

mr-son.tistory.com

https://velog.io/@jaewoneee/Webpack

 

[Webpack] BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default

해당 튜토리얼을 진행하다가 발생한 에러입니다. create-react-app으로 리액트 프로젝트 생성 후, useEffect() 안에 web3 실행시키는 코드 작성하고 yarn start 했더니, 낭자하는 에러들.... 좌우간 여기서 중

velog.io

https://github.com/ChainSafe/web3.js/issues/4090

 

web3 giving issues in Webpack 5 · Issue #4090 · ChainSafe/web3.js

I am getting the following error when running my Angular code. ./node_modules/cipher-base/index.js:2:16-43 - Error: Module not found: Error: Can't resolve 'stream' in 'D:\projects\k...

github.com

https://www.alchemy.com/blog/how-to-polyfill-node-core-modules-in-webpack-5

 

How to polyfill node core modules in webpack 5

 

www.alchemy.com

[해결]

src폴더 밑에 webpack.config.js 파일 생성하여 아래와 같이 내용 작성한 후,

module.exports = {
  resolve: {
    fallback: {
      url: require.resolve("url/"),
    },
  },
};

아래 명령을 콘솔에 입력하여 url라이브러리 설치하면 해결!

npm install url

#22 CORS 이슈, Proxy

CORS policy

server 포트 5000 / client 포트 3000

포트번호가 다른데 설정을 따로 해주지 않으면 request가 cors정책에 의해 막혀버림(보안 이슈 때문).

Cross-Origin Resource Sharing

-> Proxy로 해결할 수 있다!!

https://create-react-app.dev/docs/proxying-api-requests-in-development/

 

Proxying API Requests in Development | Create React App

Note: this feature is available with react-scripts@0.2.3 and higher.

create-react-app.dev

proxy 라이브러리 설치

npm install http-proxy-middleware --save

src/setupProxy.js 파일 생성, 내용 작성

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

module.exports = function (app) {
  app.use(
    "/api",
    createProxyMiddleware({
      target: "http://localhost:5000", //타겟 서버 포트
      changeOrigin: true,
    })
  );
};

#23 Proxy Server

유저 - proxy server - 인터넷

  1. 방화벽 기능
  2. 웹 필터 기능
  3. 캐쉬 데이터, 공유 데이터 제공 기능

 

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

#24 Concureently

프론트, 백 서버 같이 켜기

npm install concurrently --save

package.json 파일에 concurrently 코드 작성(npm run backend + (client폴더에서)npm run start)

"dev": "concurrently \"npm run backend\" \"npm run start --prefix client\""

#25 Antd CSS Framework

  • Material UI
  • React Bootstrap
  • Somatic UI
  • Ant Design
  • Materialize
  • .......

antd 설치하고 client의 index.js에서 import한 후에 client에서 에러 발생

그런데 브라우저 상에서는 에러 안보이고 똑같이 로딩되긴 함...

import문을 아래와 같이 바꾸니 에러 문구는 뜨지 않음.

import "antd/dist/antd.min.css";

#26 Redux 기초

Redux: 상태 관리 라이브러리, state container

  • props: 데이터 전달, 변화X
  • state: 변화O, re-rendering

리덕스 스토어에 state를 저장해놓으면 상위컴포넌트 혹은 하위컴포넌트를 통하지 않고 store를 통해서 state 관리를 할 수 있다.

Redux 데이터 Flow: strict unidirectional data flow, 한 방향으로만 흐름

redux data flow

  • Action: a plain object describing what happend, 객체 형식
  • Reducer: a function describing how the application's state changes, 액션을 통해 변한 state return
  • Store: 전체 application의 state들을 감싸주는 역할, 다양한 메소드로 state 관리 가능

#27 Redux Up!!

설치 라이브러리

  • redux
  • react-redux
  • redux-promise: 미들웨어
  • redux-thunk: 미들웨어
npm install redux react-redux redux-promise redux-thunk --save

redux store는 기본적으로 액션 객체 형식으로 받지만, 액션이 항상 객체 형식을 하고 있지는 않다. promise나 function형태로 된 액션을 받을 때도 있다. redux-thunck는 dispatch에게 function을 어떻게 받는지 알려주고, redux-promise는 dispatch에게 promise를 어떻게 받아들이는지 알려주어, 두 미들웨어는 객체 형식이 아닌 액션이 왔을 때에도 적절히 사용할 수 있게 돕는다.

 

//   src/index.js
.....
import { Provider } from "react-redux";
import { applyMiddleware, createStore } from "redux";
import promiseMiddleware from "redux-promise";
import ReduxThunk from "redux-thunk";
import Reducer from "./_reducers";
.....

const createStoreWithMiddleware = applyMiddleware(
  promiseMiddleware,
  ReduxThunk
)(createStore);

ReactDOM.render(
  <React.StrictMode>
    <Provider
      store={createStoreWithMiddleware(
        Reducer,
        window.__REDUX_DEVTOOLS_EXTENSION__ &&
          window.__REDUX_DEVTOOLS_EXTENSION__()
      )}
    >
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById("root")
);

 

_reduces/index.js: combineReducer로 여러 reducer들을 rootReducer 하나로 합쳐 줌.


#28 React Hooks

react component

  • class component: 많은 기능
  • functional component: 짧고 간단한 코드, 빠른 퍼포먼스

hook으로 functional component에서도 class component에서만 쓸 수 있는 기능 가능하게 됨.


#29, 30 로그인 페이지