Store
上面我们接触到如何定义 action 来表示发生了什么变化, 还有 reducer 它是如何通过不同的 action 来修改 app 的 state.
下面我们要说的 Store
, Store 是什么,从字面意思看它是用来存储什么的, 对, 它就是存储 state tree
的.
Store
有这样的作用:
- 管理app的
state
- 可以通过
getState()
来访问state
- 通过
dispatch(action)
来修改 app 的state
- 通过
subscribe(listener)
来注册监听 - 处理没有注册的监听
再次重申: Redux app 的 state
是保持在一个单独的对象里. 当需要分割处理数据的逻辑时, 应该使用复合 reducer
来替代多个 store.
如果你有 reducer,很容易来创建 store
. 上面我们使用了combineReducer()
来组合多个 reducer, 现在我们引用它然后把它传递给 createStore()
.
import { createStore } from 'redux'
import todoApp from './reducers'
let store = createStore(todoApp)
你可以通过传递一个可选的参数给
createStore()
来给 app 一个初始的状态,用来处理客户端和服务器端不同的状态(×)
let store = createStore(todoApp, window.STATE_FROM_SERVER)
分发动作
至此, 我们已经创建了 Store
, 让我们来验证 app 是否工作,我们可以在没UI 的情况下测试更新逻辑:
import { addTodo, toggleTodo, setVisibilityFilter, VisibilityFilters } from './actions'
// Log the initial state
console.log(store.getState())
// Every time the state changes, log it
// Note that subscribe() returns a function for unregistering the listener
let unsubscribe = store.subscribe(() =>
console.log(store.getState())
)
// Dispatch some actions
// 通过 store.dispatch() 方法可以模拟用户交互, 出发 action
store.dispatch(addTodo('Learn about actions'))
store.dispatch(addTodo('Learn about reducers'))
store.dispatch(addTodo('Learn about store'))
store.dispatch(toggleTodo(0))
store.dispatch(toggleTodo(1))
store.dispatch(setVisibilityFilter(VisibilityFilters.SHOW_COMPLETED))
// Stop listening to state updates
unsubscribe()

> index.js
import { createStore } from 'redux'
import todoApp from './reducers'
let store = createStore(todoApp)
**接下来我们要了解 redux app 里的数据流**
---
index
learning Redux from todo
- [learning Redux from todo[1]](http://qiita.com/xiangzhuyuan/items/a26e97c6cac476369e37)
- [learning Redux from todo[2]](http://qiita.com/xiangzhuyuan/items/86c5c6508e8481c2dd3a)
- [learning Redux from todo[3]](http://qiita.com/xiangzhuyuan/items/9ce23a8c9f3b26c48838)
- [learning Redux from todo[4]](http://qiita.com/xiangzhuyuan/items/c082e97c3b863602fccf)
- [learning Redux from todo[5]](http://qiita.com/xiangzhuyuan/items/4e6f61a27c068b4f33e7)