728x90
반응형

modules / counter.js

import { createAction, handleActions } from 'redux-actions';

const INCREASE = 'counter/INCREASE'; // action type를 변수에 저장하여 그 변수로 handleActions해준다!

const DECREASE = 'counter/DECREASE';

 

export const increase = createAction(INCREASE); // type이 지정된 변수를 careateAction()메소드를 활요하여 액션함수를 생성한다

export const decrease = createAction(DECREASE); // 이 액션함수는 사용할 클래스 내부에서 dispatch로 사용하게된다

 

const initialState = { // 리듀서

number: 0,

};

const counter = handleActions(

// 첫 번째 파라미터로는 액션에 따라 실행할 함수들을 가진 객체를 넣어주고,

// 두 번째 파라미터로는 상태의 기본 값( initialState )을 넣어준다.

{

[INCREASE]: (state, action) => ({ number: state.number + 1 }),

[DECREASE]: (state, action) => ({ number: state.number - 1 }),

},

initialState,

);

export default counter;

 

CounterContainer / contaiers.js

import React, { useCallback } from 'react';

import { useCallback, useDispatch } from 'react-redux';

import Counter from '../components/Counter';

import { increase, decrease } from '../modules/counter';

 

const CounterContainer = () => {

const number = useSelector(state => state.counter.number);  // mapStateToProps와 같은 기능이다

const dispatch = useDispatch();

const onIncrease = useCallback(() => dispatch(increase()), [dispatch]);

const onDecrease = useCallback(() => dispatch(decrease()), [dispatch]);

// useCallback()으로 최적화를 하여 dispatch되는 리듀스와 액션에 대한 state 객체가 변경이 있을 때만 함수가 재사용된다

// 위의 방법은 react-redux의 함수를 사용한 connect방법이다

 

return (

<Counter number={number} onIncrease={onIncrease} onDecrease={onDecrease} />

);

};

 

export default CounterContainer;

 

728x90
반응형

+ Recent posts

Powered by Tistory, Designed by wallel