react

리액트 기본 세팅

UTD 2023. 11. 22. 22:53


1. 리덕스

(1) 리덕스 설치

(2) src/configStore.js

(3)모듈 만들기

---스토어 조회

(1) useSelector 

(1)-2 Store 자체를 구독하는 건 지양해야 합니다

2 .yarn 에서 styled-components 설치하기

3. CRA(Create React App)→ 보일러플레이트

4.상대경로 import → 절대경로 지정하기

5, redux dev tools 설정 코드 Sample

6. react-router-dom  설치하기

6-1 [중요] Router.js 생성 및 route 설정 코드 작성 

6-2 App.js에 Router.js  import 해주기

 


1. 리덕스


(1) 리덕스 설치
yarn add redux react-redux

# 아래와 같은 의미
yarn add redux
yarn add react-redux
=========================================


(2) src/configStore.js
src/configStore.js 에 아래 코드를 입력하세요.
==========================================
import { createStore } from "redux";
import { combineReducers } from "redux";
// reducer import 해와야됨.
/*
1. createStore()
리덕스의 가장 핵심이 되는 스토어를 만드는 메소드(함수) 입니다. 
리덕스는 단일 스토어로 모든 상태 트리를 관리한다고 설명해 드렸죠? 
리덕스를 사용할 시 creatorStore를 호출할 일은 한 번밖에 없을 거예요.
*/

/*
2. combineReducers()
리덕스는 action —> dispatch —> reducer 순으로 동작한다고 말씀드렸죠? 
이때 애플리케이션이 복잡해지게 되면 reducer 부분을 여러 개로 나눠야 하는 경우가 발생합니다. 
combineReducers은 여러 개의 독립적인 reducer의 반환 값을 하나의 상태 객체로 만들어줍니다.
*/

const rootReducer = combineReducers({
// 여기에  reudcer추가
}); 
const store = createStore(rootReducer); 

export default store; 

===============================================
- **(3) index.js**
    
    디렉토리의 가장 최상단에 있는 `index.js`에 아래 내용을 입력하세요.
================================================
// 원래부터 있던 코드
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

// 우리가 추가할 코드
import store from "./redux/config/configStore";
import { Provider } from "react-redux";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(

//App을 Provider로 감싸주고, configStore에서 export default 한 store를 넣어줍니다.
  <Provider store={store}> 
    <App />
  </Provider>
);

// 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();
======================================================

(3)모듈 만들기
===================================================

modules / todos.js


// 각 모듈에는 하나의 state와 연관된 액션 타입, 액션 생성자 함수, 리듀서들이 각각 정의된다.

// 액션 타입 정의 (액션 생성자와 리듀서에서 참조하는 용도)
const DELETE_TODO = "todo/DELETE_TODO";

// 액션 생성자 정의 (컴포넌트 내에서 import 해서 사용하는 용도)
export const deleteTodo = (payload) => {
return {
type: DELETE_TODO,
payload
}
}

// 초기 상태값
const initialState = []; // const [todos, setTodos] = useState([]);

// 리듀서
const todos = (state = initialState, action) => {
  switch (action.type) {
case DELETE_TODO:
const id = action.payload;
const newTodos = state.filter(todo => todo.id !== id);
return newTodos;
    default:
      return state;
  }
};

// 모듈파일에서는 리듀서를 export default 한다.
export default todos;

===========================================

(1) useSelector = 스토어 조회
======================================
// src/App.js

import React from "react";
import { useSelector } from "react-redux"; // import 해주세요.

const App = () => {
  const counterStore = useSelector((state) => state); // 추가해주세요.
  console.log(counterStore); // 스토어를 조회해볼까요?

  return <div></div>;
}

export default App;

===========================================
(1)-2 Store 자체를 구독하는 건 지양해야 합니다.
===========================================
// 💩 이러시면 안됩니다. 불필요하게 리렌더링이 발생할 수 있습니다.
const store = useSelector(state => state);
const todos = store.todos;

// 🎉 Good!
const todos = useSelector(state => state.todos);
=======================================

2 .yarn 에서 styled-components 설치하기
=======================================
yarn add styled-components
=======================================

3. CRA(Create React App)→ 보일러플레이트
=======================================
ls #현재 내가 위치하고 있는 곳이 어디인지 확인해보세요.

cd 폴더이름 #리액트 프로젝트를 생성하고 싶은 폴더로 들어갑니다.

yarn create react-app week-1 #프로젝트 생성!

==========================================

4.상대경로 import → 절대경로 지정하기
jsconfig.json 파일을 만들어주세요(반드시 root 경로에 만드세요)
===========================================
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
===========================================
5, redux dev tools 설정 코드 Sample

===================================

yarn add redux-devtools-extension

=================================
configStore.js 에서 


import { combineReducers, createStore } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import todos from "../modules/todos";
import auth from "../modules/auth";

const rootReducer = combineReducers({ todos, auth });

const store = createStore(rootReducer, composeWithDevTools());

export default store;
=============================================
6. react-router-dom  설치하기

============================================
yarn add react-router-dom 

=============================================
6-1
[중요] Router.js 생성 및 route 설정 코드 작성 
src안에 shared 라는 폴더를 생성해주고, 그 안에 Router.js  파일을 생성
=============================================

import React from "react";
// 1. react-router-dom을 사용하기 위해서 아래 API들을 import 합니다.
import { BrowserRouter, Route, Routes } from "react-router-dom";

// 2. Router 라는 함수를 만들고 아래와 같이 작성합니다.
//BrowserRouter를 Router로 감싸는 이유는, 
//SPA의 장점인 브라우저가 깜빡이지 않고 다른 페이지로 이동할 수 있게 만들어줍니다!
const Router = () => {
  return (
    <BrowserRouter>
      <Routes>
<Route path = " ", element ={ <   /> } />
      </Routes>
    </BrowserRouter>
  );
};

export default Router;
=================================================
6-2 App.js에 Router.js  import 해주기
App 컴포넌트에 넣어주는 이유는 우리가 만든 프로젝트에서 가장 최상위에 존재하는 컴포넌트가 App.js 이기 때문
=================================================
import React from "react";
import Router from "./shared/Router";

function App() {
  return <Router />;
}

export default App;

============================================