// Устройство функции createStore()
const defaultState = {
counter: 0
};
function createUpAction (value) {
return {
type: 'UP',
value: value
};
}
function counterReducer (state = defaultState, action) {
const stateCopy = lodash.cloneDeep(state);
switch (action.type) {
case 'UP':
stateCopy.counter += action.value;
return stateCopy;
case 'DOWN':
stateCopy.counter -= action.value
return stateCopy;
default:
return state;
}
}
const store = createStore(counterReducer);
store.dispatch(createUpAction(1));
store.getState(); // {counter: 1}
function createStore (reducer, initialState) {
let state = initialState;
return {
dispatch: (action) => {state = reducer(state, action);},
getState: () => {return state;}
}
}
Устройство функции combineReducers()
const reducer = combineReducers({
todoState: todoReducer,
counterState: counterReducer
})
function counterReducer (state, action) {
if (action.type === 'ADD') {
return state + 1;
} else {
return state;
}
}
const initialState = {
todoState: [],
counterState: 0,
}
const store = createStore(reducer, initialState);
function combineReducers (reducersMap) {
return function combinationReducer (state, action) {
const nextState = {};
Object.entries(reducersMap).forEach(([key, reducer]) => {
nextState[key] = reducer(state[key], action);
});
return nextState;
}
}
Устройство функции applyMiddleware()
const createStoreWithMiddleware = applyMiddleware(someMiddleware)(createStore);
const store = createStoreWithMiddleware(reducer, initialState);
const thunk = (store) => (dispatch) => (action) => {
if (typeof action === 'function') {
return action(store.dispatch, store.getState);
}
return dispatch(action);
}
function createStore (reducer, initialState) {
let state = initialState;
return {
dispatch: (action) => {state = reducer(state, action);},
getState: () => {return state;}
}
}
function applyMiddleware (middleware) {
return function createStoreWithMiddleware (createStore) {
return (reducer, state) => {
const store = createStore(reducer, state);
return {
dispatch: action => middleware(store)(store.dispatch)(action),
getState: store.getState
}
}
}
}
Комментариев нет:
Отправить комментарий