Redux(4)

김현진·2022년 2월 2일
0

1. combineReducers

- redux로 부터 import
- 복잡한 스테이트를 관리할 때 사용

2. 예시

// reducers.js

import {combineReducers} from "redux";
import todos from './todos';
import filter from './filers';

const reducer = combineReducers({
    todos,
    filter
});

export default reducer;

state 별로 분리를 실시


//todos.js

import {ADD_TODO, COMPLETE_TODO} from "../action";

const initialState = [];

export default function todos(previousState=initialState, action) {
    switch (action.type) {
        case ADD_TODO:
            return [...previousState, { text: action.text, done: false }];

        case COMPLETE_TODO:
            return previousState.map((todo, i) => {
                if(action.index === i) {
                    return { ...todo, done: true};
                }
                return todo;
            })

        default:
            return previousState;
    }
}

// filters.js

import {SHOW_ALL, SHOW_COMPLETE} from "../action";

const initialState = 'ALL';

export default function filterReducer(previousState=initialState, action) {
    switch (action.type) {
        case SHOW_COMPLETE:
            return 'COMPLETE';

        case SHOW_ALL:
            return 'ALL';

        default:
            return previousState;
    }
}
// action.js
// type 선언
export const ADD_TODO = 'ADD_TODO';
export const COMPLETE_TODO = 'COMPLETE_TODO';
export const SHOW_ALL = 'SHOW_ALL';
export const SHOW_COMPLETE = 'SHOW_COMPLETE';

export function addTodo(todo) {
    return {
        type: ADD_TODO,
        todo
    }
}

export function completeTodo(index) {
    return {
        type: COMPLETE_TODO,
        index
    }
}

export function showAll() {
    return {
        type: SHOW_ALL
    }
}

export function showComplete() {
    return {
        type: SHOW_COMPLETE
    }
}```
profile
기록의 중요성

0개의 댓글