0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

learning Redux from todo[3]

Last updated at Posted at 2016-09-11

Store

上面我们接触到如何定义 action 来表示发生了什么变化, 还有 reducer 它是如何通过不同的 action 来修改 app 的 state.

下面我们要说的 Store , Store 是什么,从字面意思看它是用来存储什么的, 对, 它就是存储 state tree 的.

Store 有这样的作用:

  • 管理app的 state
  • 可以通过 getState()来访问 state
  • 通过 dispatch(action)来修改 app 的 state
  • 通过 subscribe(listener)来注册监听
  • 处理没有注册的监听

再次重申: Redux appstate 是保持在一个单独的对象里. 当需要分割处理数据的逻辑时, 应该使用复合 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()


![](http://i.imgur.com/zMMtoMz.png)

> 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)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?