import { createActions, handleActions } from 'redux-actions';
import produce from 'immer';
const SET_SOMETHING = 'summary/SET_SOMTHING';
// ...
export const { setSomething } = createActions(
{
SET_SOMETHING: somthing => something,
// ...
},
{
prefix: 'summary',
}
);
const summaryReducer = handleActions(
{
[SET_SOMETHING]: (state, action) => {
return produce(state, draft => {
draft.something = action.payload;
});
},
// ...
},
initalState
);
export default summaryReducer;
switch
문을 사용합니다.case
마다 함수를 정의해야 해서 코드 중첩이 생겨서 가독성이 떨어집니다.import produce from 'immer';
const nextState = produce(state, draft => {
draft[1].floor = 'Ground Floor';
});
import { createSlice } from '@reduxjs/toolkit'
const initialState = {
value: 0
};
const {actions, reducer} = createSlice({
name: 'counter',
initialState,
reducers: {
increment: (state) => {
state.value++
},
decrement: (state) => {
state.value--
},
incrementByAmount: (state, action) => {
state.value += action.payload
},
},
})
export const { increment, decrement, incrementByAmount } = actions;
export default reducer;
import React, { createContext, useContext, useReducer } from 'react';
const TasksContext = createContext(null);
const TasksDispatchContext = createContext(null);
export const useTasks = () => useContext(TasksContext);
export const useTasksDispatch = () => useContext(TasksDispatchContext);
export const TasksProvider = ({ children }) => {
const [tasks, dispatch] = useReducer(
reducer,
initialState
);
return (
<TasksContext.Provider value={tasks}>
<TasksDispatchContext.Provider value={dispatch}>
{children}
</TasksDispatchContext.Provider>
</TasksContext.Provider>
);
}
const initialState = [
{ id: 0, text: 'Philosopher’s Path', done: true },
{ id: 1, text: 'Visit the temple', done: false },
{ id: 2, text: 'Drink matcha', done: false }
];
const { actions, reducer } = createSlice({
name: 'tasks',
initialState,
reducers: {
added: (state, action) => {
state.push(action.payload);
},
changed: (state, action) => {
state = state.map(task => {
if (task.id === action.payload.id) {
return action.payload;
}
return task;
})
},
deleted: (state, action) => {
state = state.filter(task => task.id !== action.payload.id);
},
}
});
export const {
added,
changed,
deleted,
} = actions;
export default reducer;
Reducer와 Context로 앱 확장하기 – React