четверг, 23 ноября 2017 г.

Redux Очень короткая шпаргалка

import {createStore, combineReducers, applyMiddleware} from 'redux';

// Counter

var counterActionType = {
    'UP': 'UP'
};

function couterActionCreator (value) {
    return {
  type: counterActionType.UP,
        value: value
    };
}

function counterReducer (state, action) {
    if (state === undefined) {state = {counter: 0};}
    switch (action.type) {
        case counterActionType.UP: return Object.assign({}, state, {counter: state.counter + action.value});
        default: return state;
     }
}

// Time

var timeActionType = {
    'UPDATE': 'UPDATE'
};

function timeActionCreator (value) {
    return {
        type: timeActionType.UPDATE,
        value: value
    };
}

function timeReducer (state, action) {
    if (state === undefined) {state = {time: new Date()};}
    switch (action.type) {
        case timeActionType.UPDATE: return Object.assign({}, state, {time: new Date(state.time.getTime() + action.value)});
        default: return state;
    }
}

var rootReducer = combineReducers({
    counterObject: counterReducer,
    timeObject: timeReducer
});

var initialState = {
    counterObject: {counter: 2},
    timeObject: {time: new Date()}
};

var store = createStore(rootReducer, initialState, applyMiddleware(/* createLogger(), thunkMiddleware */));

var unsubscribeStore = store.subscribe(function storeChangeListener () {
    console.log(store.getState());
});

console.log(store.getState().counterObject.counter);

store.dispatch(couterActionCreator(1));

console.log(store.getState().counterObject.counter);

unsubscribeStore();

store.dispatch(couterActionCreator(1));

console.log(store.getState().counterObject.counter);

store.dispatch(timeActionCreator(1000000));

console.log(store.getState().timeObject.time);

Комментариев нет:

Отправить комментарий