typesafe-actions
3534 단어 reduxtypescriptReactReact
typesafe-actions 라이브러리
action을 일일이 만들어주어야 하는 원래 방식과는 달리
createStandardAction을 사용하면 action을 쉽게 만들어서 사용할수있다.
적용전 code
const INCREASE = 'counter/INCREASE' as const;
const DECREASE = 'counter/DECREASE' as const;
const INCREASE_BY = 'counter/INCREASE_BY' as const;
export const increase = () => ({
type: INCREASE
})
export const decrease = () => ({
type: DECREASE
})
export const increaseBy = (diff: number) => ({
type: INCREASE_BY,
payload: diff
})
type CounterAction =
| ReturnType<typeof increase>
| ReturnType<typeof decrease>
| ReturnType<typeof increaseBy>;
type CounterState = {
count: number;
}
const initialState: CounterState = {
count: 0
};
function counter(
state: CounterState = initialState,
action: CounterAction
) : CounterState {
switch(action.type){
case INCREASE:
return {count: state.count + 1};
case DECREASE:
return {count: state.count - 1};
case INCREASE_BY:
return {count: state.count + action.payload};
default:
return state;
}
}
export default counter;
적용후 코드
// ** typesafe-actions 라이브러리 사용
import {deprecated, ActionType, createReducer} from 'typesafe-actions';
const {createStandardAction} = deprecated
// // 액션 type 선언
const INCREASE = 'counter/INCREASE';
const DECREASE = 'counter/DECREASE';
const INCREASE_BY = 'counter/INCREASE_BY';
// 액션 생성함수를 선언합니다
export const increase = createStandardAction(INCREASE)();
export const decrease = createStandardAction(DECREASE)();
export const increaseBy = createStandardAction(INCREASE_BY)<number>(); // payload 타입을 Generics 로 설정해주세요.
const actions = { increase, decrease, increaseBy};
type CounterAction = ActionType<typeof actions>;
type CounterState = {
count: number;
};
const initialState: CounterState = {
count : 0
};
// 객체 형식으로 입력
const counter = createReducer<CounterState, CounterAction>(initialState, {
[INCREASE] : state => ({ count: state.count + 1}),
[DECREASE]: state => ({ count: state.count - 1}),
[INCREASE_BY]: (state, action) => ({ count: state.count + action.payload })
});
export default counter;
** 참고 : https://react.vlpt.us/using-typescript/05-ts-redux.html
Author And Source
이 문제에 관하여(typesafe-actions), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@vmelove/typesafe-actions저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)