๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

react/redux

[React] redux-actions๋กœ ๊ฐ€๋…์„ฑ ๋†’์ด๊ธฐ

๐Ÿ”ธ redux-actions

yarn add redux-actions

  • ์•ก์…˜ ์ƒ์„ฑ ํ•จ์ˆ˜๋ฅผ ๋” ์งง์€ ์ฝ”๋“œ๋กœ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ค€๋‹ค.
  • ๋ฆฌ๋“€์„œ๋ฅผ ์ž‘์„ฑํ•  ๋•Œ switch๋ฌธ์ด ์•„๋‹Œ handleActions๋ผ๋Š” ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ค€๋‹ค.

 

๐Ÿ”ธ createAction

  • ์•ก์…˜ ์ƒ์„ฑ ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด์ฃผ๋Š” ํ•จ์ˆ˜์ด๋‹ค.
  • ์ง์ ‘ ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค ํ•„์š” ์—†์–ด ํ›จ์”ฌ ๊ฐ„๋‹จํ•˜๋‹ค.

createAction์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•˜์„ ๋•Œ

const CHANGE_USER = 'user/CHANGE_USER';
// ์•ก์…˜ ์ƒ์„ฑ ํ•จ์ˆ˜
export const change_user = user => ({type: CHANGE_USER, user});

createAction์„ ์‚ฌ์šฉํ–ˆ์„ ๋•Œ

import { createAction } from 'redux-actions';
const CHANGE_USER = 'user/CHANGE_USER';
// ์•ก์…˜ ์ƒ์„ฑ ํ•จ์ˆ˜
export const change_user = createAction(CHANGE_USER, user => user);

 

๐Ÿ”ธ handleActions

  • handleActions๋กœ ๋ฆฌ๋“€์„œ๋ฅผ ๋” ๊ฐ„๋‹จํ•˜๊ฒŒ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.

handleActions์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•˜์„ ๋•Œ

const reducer = (state = initState, action) => {
	switch (action.type) {
		case CHANGE_USER:
			return {
					...state,
					user: action.user
			}
	}
}

handleActions์„ ์‚ฌ์šฉํ–ˆ์„ ๋•Œ

import { handleActions } from 'redux-actions';
const reducer = handleActions({
	[CHANGE_USER]: (state, action) => ({...state, user: action.user})
});

 

๋ฐ˜์‘ํ˜•