1. Redux : state 관리 라이브러리임

- state : 컴포넌트 안에서 데이터를 전달하는 방식이며, 컴포넌트 안에서도 충분히 값을 변경할 수 있음
state가 변하면 re-rending 되는 특징이 있음
- props는 부모에서 자식 방향으로 값을 보내, 변하지 않는 값을 의미하며 생성할 때 전달하는 값임
=> redux는 state를 관리해주는 tool임

- 데이터를 공유하는 컴포넌트들이 계층적으로 존재한다면, 계속해서 부모와 자식 사이를 지나가며 상태를 유지해야 함
- 그러나, redux를 사용한다면 store 하나를 만들어 컴포넌트들의 상태를 관리할 수 있음

- Redux data flow : 철저하게 한방향으로 흐르는 것을 의미함

- Action : 어떤 일이 일어났는지 설명하는 객체

- Reducer : 이전 state와 action object를 받아 next state를 반환
- Store : 전체적인 어플리케이션 state를 감싸고 있는 역할
2. Redux 설정
- 설치
npm install redux react-redux redux-promise redux-thunk --save
- store를 변경하려면, dispatch를 이용하여 action을 일으키는 방법으로만 가능하지만, 언제나 action 객체를 받는 것은 아님
- promise나 functions 형태로도 받을 수 있으며, 이를 해결하기 위해 redux-promise와 redux-thunk 미들웨어를 설치한 것임
- createStore은 그냥 store는 객체밖에 못 받기 때문에, promiseMiddleware와 ReduxThunk를 같이 미들웨어로 받기 위해 사용함
- src/index.js 추가
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Provider } from 'react-redux';
import 'antd/dist/antd.css';
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(
<Provider
store={createStoreWithMiddleware(Reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__()
)}
>
<React.StrictMode>
<App />
</React.StrictMode>
</Provider>
,document.getElementById('root')
);
// 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();
=> Provider 안에 store를 추가한 뒤에 App을 감싸면 redux를 연결할 수 있음
reducer가 있어야 연결할 수 있기 때문에 임의로 하나 작성함
Redux DevTools
Redux DevTools for debugging application's state changes.
chrome.google.com
=> 리덕스의 개발자 도구를 사용하면 현재 스토어의 상태를 개발자 도구에서 조회할 수 있고,
지금까지 어떤 액션들이 디스패치 되었는지, 그리고 액션에 따라 상태가 어떻게 변화했는지 확인할 수 있고,
추가적으로 액션을 직접 디스패치 할 수도 있음
- src/_reducer/index.js
import { combineReducers } from "redux";
//import user from './user_reducer';
const rootReducer = combineReducers({
//user,
})
export default rootReducer;
=> reducer는 state가 변환된 것을 계산하여 돌려주는 역할을 하며, 이러한 reducer는 여러 개가 존재할 수 있음
combineReducers는 여러 개의 reducer를 root reducer에서 합쳐주는 역할을 함
'Web > React Node js' 카테고리의 다른 글
리액트 기초 강의 (9) - 로그인 페이지 (0) | 2022.03.02 |
---|---|
리액트 기초 강의 (8) - React Hooks (0) | 2022.03.01 |
리액트 기초 강의 (6) - Antd CSS Framework (0) | 2022.03.01 |
리액트 기초 강의 (5) - Concurrently (0) | 2022.03.01 |
리액트 기초 강의 (4) - Proxy server (0) | 2022.03.01 |
댓글