1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| import {createStore, combineReducers, applyMiddleware} from 'redux' import ReduxThunk from 'redux-thunk' import { composeWithDevTools} from 'redux-devtools-extension'
const initialState = { count: 0 }
const userInitialState = { username: 'john' }
const ADD = 'ADD' function counterReducer(state = initialState, action) { console.log(state, action) switch (action.type) { case ADD: return {count: state.count + (action.num || 1) } default: return state } } const UPDATE_NAME = 'UPDATE_NAME' function userReducer(state= userInitialState, action) { switch(action.type) { case UPDATE_NAME: return {...state, username: action.name} default: return state } }
const allReducers = combineReducers({ counter: counterReducer, user: userReducer })
const store = createStore(allReducers, { counter: initialState, user: userInitialState }, composeWithDevTools(applyMiddleware(ReduxThunk)) );
function add(num) { return { type: ADD, num, } }
function addAsync(num) { return (dispatch, getState) => setTimeout(()=>{ dispatch(add(num)) }, 1000) }
console.log(store.getState()) store.dispatch({type: ADD}) console.log(store.getState())
store.subscribe(()=>{ console.log('changed', store.getState()) })
store.dispatch(add(3))
store.dispatch(addAsync(5)) store.dispatch({type: UPDATE_NAME, name: 'Yehya'})
export default store
|