함수형 리덕스 예시

Column 1
Tags
example
Column

Actions.js

  • Actions + ActionCreator
/* 액션 타입 정의 */ // 액션 타입은 주로 대문자로 작성합니다. export const INCREASE = 'INCREASE'; export const DECREASE = 'DECREASE'; export const CHANGE_TEXT = 'CHANGE_TEXT'; export const ADD_TO_LIST = 'ADD_TO_LIST'; /* 액션 생성함수 정의 */ // 액션 생성함수는 주로 camelCase 로 작성합니다. export function increase() { return { type: INCREASE // 액션 객체에는 type 값이 필수입니다. }; } // 화살표 함수로 작성하는 것이 더욱 코드가 간단하기에, // 이렇게 쓰는 것을 추천합니다. export const decrease = () => ({ type: DECREASE }); export const changeText = text => ({ type: CHANGE_TEXT, text // 액션안에는 type 외에 추가적인 필드를 마음대로 넣을 수 있습니다. }); export const addToList = item => ({ type: ADD_TO_LIST, item });
 

Reducer.js

  • Reducer
import { createStore } from 'redux'; // createStore는 스토어를 만들어주는 함수입니다. // 리액트 프로젝트에서는 단 하나의 스토어를 만듭니다. //액션 import {INCREASE, DECREASE, CHANGE_TEXT, ADD_TO_LIST} from './actions' /* 리덕스에서 관리 할 상태 정의 */ const initialState = { counter: 0, text: '', list: [] }; /* 리듀서 만들기 */ // 위 액션 생성함수들을 통해 만들어진 객체들을 참조하여 // 새로운 상태를 만드는 함수를 만들어봅시다. // 주의: 리듀서에서는 불변성을 꼭 지켜줘야 합니다! export function reducer(state = initialState, action) { // state 의 초깃값을 initialState 로 지정했습니다. switch (action.type) { case INCREASE: return { ...state, counter: state.counter + 1 }; case DECREASE: return { ...state, counter: state.counter - 1 }; case CHANGE_TEXT: return { ...state, text: action.text }; case ADD_TO_LIST: return { ...state, list: state.list.concat(action.item) }; default: return state; } }
 

App.js

  • reducer 등록
... //Redux import { createStore } from 'redux' import { Provider } from 'react-redux' import { reducer } from './Redux/reducer' ... //store 생성해서 Provier에 전달해야함. const store = createStore(reducer); console.log(store.getState()); //테스트용으로 초기 상태 출력 export default function App() { return ( //Provier로 감싸고, store 전달 <Provider store={store} > ... </Provider> ); } ...
 

PMain.js

  • 화면에서 redux 상태 접근 예시
... import { useSelector, useDispatch } from 'react-redux'; import {increase} from '../../Redux/actions' //액션과 액션함수가 담긴 곳에서 액션함수 임포트 //따로 props로 안받아와도 state 접근 가능. export default function PMain({ navigation }) { ... //state 값 가져오기 const { counter, text, list } = useSelector( (state) => ({ counter: state.counter, text: state.text, list: state.list })); //dispatch Hook으로 액션함수 넘겨주면 됨. const usedisplay = useDispatch(); usedisplay(increase()); //인자가 있는 함수라면 대충 아래와 같다. //usedisplay( hello => increase(hello) ); //액션 생성함수 말고, 직접 액션을 넘겨도 된다. //예시는 생략 return ( <> ... </> ); } ...
 

여러 Reducer 합쳐서 쓰기

  • Reducer/reducers.js
import { combineReducers } from 'redux'; import {locationReducer} from './locationReducer' import {dialogReducer} from './dialogReducer' export default combineReducers({ locationReducer: locationReducer, dialogReducer: dialogReducer, });
 
  • 이러고 상태(state)에 접근 시에는 아래처럼 접근하면 됨.
const {locations} = useSelector((state) => ({ locations: state.locationReducer.locations }))