typesafe-actions


typesafe-actionsライブラリ


アクションを1つずつ作成しなければならない元の方法とは異なります
createStandardActionを使用すると、簡単にアクションを作成および使用できます.

プリコードの適用

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