// 1 defines the ACTION constant
const ADD_COUNT = 'ADD_COUNT'
const MINUS_COUNT = 'MINUS_COUNT'
const CUSTOM_COUNT = 'CUSTOM_COUNT'
const PUSH_TODO = 'PUSH_TODO'
const POP_TODO = 'POP_TODO'

// 2 Defines the initial value
const initCount = { count: 0 }
const initTodo = { list: []}// 3 Define reducer (equivalent to mutation of vuex, but not directly modify state, but return new state, i.e. pure function)
const counter = function (state = initCount, action) {
  switch (action.type) {
    case ADD_COUNT:
      return { count: state.count + 1 }
    case MINUS_COUNT:
      return { count: state.count - 1 }
    case CUSTOM_COUNT:
      return { count: action.payload.count }
    default:
      break
  }
  return state
}
const todos = function (state = initTodo, action) {
  switch (action.type) {
    case PUSH_TODO:
      return { list: state.list.concat(action.payload.todo) }
    case POP_TODO:
      return { list: state.list.slice(0, state.list.length - 1)}default:
      break
  }
  return state
}

// 4 Define action creater (encapsulate action for external call)
let addCount = () = > {
  return { type: ADD_COUNT }
}
let minusCount = () = > {
  return { type: MINUS_COUNT }
}
let customCount = (count) = > {
  return { type: CUSTOM_COUNT, payload: { count } }
}
let pushTodo = (todo) = > {
  return { type: PUSH_TODO, payload: { todo } }
}
let popTodo = () = > {
  return { type: POP_TODO }
}

// 5 Create store,combineReducers similar to vuex merge module
const store = createStore(combineReducers({ counter, todos }))

// 6 Create an action trigger function, optional
addCount = bindActionCreators(addCount, store.dispatch)
minusCount = bindActionCreators(minusCount, store.dispatch)
customCount = bindActionCreators(customCount, store.dispatch)
pushTodo = bindActionCreators(pushTodo, store.dispatch)
popTodo = bindActionCreators(popTodo, store.dispatch)

// 7 Listen for state changes. This is optional and is generally used to process service logic
store.subscribe(() = > console.log(store.getState()))
Copy the code