章节 6 - dispatch-action.js

迄今为止我们的关注点都是绑定我们的 reducer,但我们还未 dispatch 任何一个 action。

我们将会用到上一章的 reducer ,并用它们处理一些 action:

  1. var userReducer = function (state = {}, action) {
  2. console.log('userReducer was called with state', state, 'and action', action)
  3. switch (action.type) {
  4. case 'SET_NAME':
  5. return {
  6. ...state,
  7. name: action.name
  8. }
  9. default:
  10. return state;
  11. }
  12. }
  13. var itemsReducer = function (state = [], action) {
  14. console.log('itemsReducer was called with state', state, 'and action', action)
  15. switch (action.type) {
  16. case 'ADD_ITEM':
  17. return [
  18. ...state,
  19. action.item
  20. ]
  21. default:
  22. return state;
  23. }
  24. }
  25. import { createStore, combineReducers } from 'redux'
  26. var reducer = combineReducers({
  27. user: userReducer,
  28. items: itemsReducer
  29. })
  30. var store_0 = createStore(reducer)
  31. console.log("\n", '### It starts here')
  32. console.log('store_0 state after initialization:', store_0.getState())
  33. // 输出:
  34. // store_0 state after initialization: { user: {}, items: [] }

让我们来 dispatch 我们的第一个 action… 记住在 ‘simple-action-creator.js’ 中所提到的: “为了 dispatch 一个 action,我们需要一个 dispatch 函数。”

我们所看到的 dispatch 函数,是 Redux 提供的,并且它会将 action 传递给任何一个 reducer!dispatch 函数本质上是 Redux 的实例的属性 “dispatch”

dispatch 一个 action:

  1. store_0.dispatch({
  2. type: 'AN_ACTION'
  3. })
  4. // 输出:
  5. // userReducer was called with state {} and action { type: 'AN_ACTION' }
  6. // itemsReducer was called with state [] and action { type: 'AN_ACTION' }

每一个 reducer 都被调用了,但是没有一个 action type 是 reducer 需要的,因此 state 是不会发生变化的:

  1. console.log('store_0 state after action AN_ACTION:', store_0.getState())
  2. // 输出:store_0 state after action AN_ACTION: { user: {}, items: [] }

但是,等一下!我们是不是可以用一个 action creator 去发送一个 action?我们确实可以用一个 actionCreator,但由于它只是返回一个 action,那么就意味着它不会携带任何东西到这个例子中。但为了面对未来遇到的困难,我们还是以正确的方式,即以 flux 理论去做吧。让我们使用这个 action creator 发送一个我们想要的 action:

  1. var setNameActionCreator = function (name) {
  2. return {
  3. type: 'SET_NAME',
  4. name: name
  5. }
  6. }
  7. store_0.dispatch(setNameActionCreator('bob'))
  8. // 输出:
  9. // userReducer was called with state {} and action { type: 'SET_NAME', name: 'bob' }
  10. // itemsReducer was called with state [] and action { type: 'SET_NAME', name: 'bob' }
  11. console.log('store_0 state after action SET_NAME:', store_0.getState())
  12. // 输出:
  13. // store_0 state after action SET_NAME: { user: { name: 'bob' }, items: [] }

我们刚刚处理了一个 action,并且它改变了应用的 state!

但是这似乎太简单了,并且还不足以充当一个真实的用例。例如, 如果我们要在 dispatch action 之前做一些异步的操作,那应该怎么做呢? 我们将在下一章节 “dispatch-async-action.js” 中讨论这个问题

至止,我们接触的应用流程是这样的: ActionCreator -> Action -> dispatcher -> reducer

下一章节:07_dispatch-async-action-1.js