Redux Study Day4 - Store
- Redux Study Day1 - Start
- Redux Study Day2 - Action
- Redux Study Day3 - Reducer
- Redux Study Day4 - Store
繼前面的 action/reducer 之後,接下來就是要把這兩者結合起來了~
Store
當你寫完 action/reducer 之後,大概還不太能理解,這兩個東西要怎麼串在一起?
Store 就是把 action/reducer 串在一起的物件
所以先來說說 Store 的責任:
- 掌管應用程式狀態;
- 允許藉由 getState() 獲取 state;
- 允許藉由 dispatch(action) 來更新 state;
- 藉由 subscribe(listener) 註冊 listeners;
- 藉由 unsubscribe(listener) 回傳的 function 處理撤銷 listeners。
根據上面的 Flux 架構圖,action 需要透過 dispatcher 來變更 Store 的狀態。
所以,我們在寫完 reducer 之後,可以透過 Redux 提供的 createStore
方法來把 reducer 放入 Store 中
1 | import { combineReducers, createStore } from 'redux' |
2 | let reducer = combineReducers({ visibilityFilter, todos }) |
3 | let store = createStore(reducer) |
Dispatch Actions
當 Store 建立之後,你只要透過 store.dispatch(action)
的方式,就可以透過 action 來變更 State 了。
1 | import { addTodo, completeTodo, setVisibilityFilter, VisibilityFilters } from './actions' |
2 | |
3 | store.dispatch(addTodo('Learn about actions')) |
4 | store.dispatch(addTodo('Learn about reducers')) |
5 | store.dispatch(addTodo('Learn about store')) |
6 | store.dispatch(completeTodo(0)) |
7 | store.dispatch(completeTodo(1)) |
8 | store.dispatch(setVisibilityFilter(VisibilityFilters.SHOW_COMPLETED)) |
心得
因為 action/reducer 以及 Store 本身,都是單純的 javascript functions,所以在 UI 還沒有建立的時候,你其實可以透過 Store 的 subscribe/unsubscribe 方法,來觀察 State 物件的變化
藉此來得知,action/reducer 的邏輯是否正確
修改以下上面的程式碼:
1 | import { addTodo, completeTodo, setVisibilityFilter, VisibilityFilters } from './actions' |
2 | |
3 | // 訂閱每次的變更 |
4 | let unsubscribe = store.subscribe(() => { |
5 | console.log(store.getState()); |
6 | }); |
7 | |
8 | store.dispatch(addTodo('Learn about actions')) |
9 | store.dispatch(addTodo('Learn about reducers')) |
10 | store.dispatch(addTodo('Learn about store')) |
11 | store.dispatch(completeTodo(0)) |
12 | store.dispatch(completeTodo(1)) |
13 | store.dispatch(setVisibilityFilter(VisibilityFilters.SHOW_COMPLETED)) |
14 | |
15 | // 取消訂閱 |
16 | unsubscribe(); |
你就可以從 console 看到資料的變化 (圖片來源) :