## store
前面我們可以使用`action`對象來描述"發生了什么",使用`action`創建函數來返回一個`action`對象。
還可以使用`reducers`來根據`action`更新`state`。
那我們怎么提交一個`action`對象來觸發`reducers`更新`state`呢?
`store`就是把它們聯系到一起的對象。`store`有以下職責:
* 維持應用的`state`
* 提供`getState()`方法獲取`state`
* 提供`dispatch(action)`觸發`reducers`方法更新`state`(這就是主要修改`state`的方法)
* 通過`subscribe(listener)`注冊監聽器
* 通過`subscribe(listener)`返回的函數注銷監聽器
`src/redux/store.js`
~~~
import { createStore } from 'redux'
import combineReducers from './reducers.js'
// createStore需要一個對象來初始化store: let store = createStore(combineReducers)
export default createStore(combineReducers)
~~~
到目前為止,我們已經創建了一個`redux`了~
接下來就是使用了:
~~~
cd src
cd redux
touch testRedux.js
~~~
`src/redux/testRedux.js`
~~~
import {increment, decrement, reset} from './actions/counter';
import store from './store';
// 打印初始狀態
console.log(store.getState());
// 每次 state 更新時,打印日志
// 注意 subscribe() 返回一個函數用來注銷監聽器
let unsubscribe = store.subscribe(() =>
console.log(store.getState())
);
// 發起一系列 action
store.dispatch(increment());
store.dispatch(decrement());
store.dispatch(reset());
// 停止監聽 state 更新
unsubscribe();
~~~
當前文件夾執行命令
~~~
webpack testRedux.js build.js
node build.js
~~~
是不是看到輸出了state變化?
~~~
{ counter: { count: 0 } }
{ counter: { count: 1 } }
{ counter: { count: 0 } }
{ counter: { count: 0 } }
~~~
做這個測試,就是為了告訴大家,redux和react沒關系,雖說他倆能合作。
到這里,我建議你再理下redux的數據流,看看[這里](http://cn.redux.js.org/docs/basics/DataFlow.html)。
1. 調用`store.dispatch(action)`提交一個`action`對象。
2. `redux store`調用傳入的`reducer`函數。把當前的`state`和`action`傳進去。
3. 根`reducer`應該把多個子`reducer`合并成一個單一的`state`。
4. `Redux store`保存了根`reducer`(第三步)返回的單一完整的`state`。
整個流程如上所述。
下一節我們開始搭配react使用。