Redux:store

时间:2025-02-25 11:05:27

Store是一个对象。他有如下职责:

1.存放state

2.对外提供访问state的接口: getState()

3.允许state更新:dispatch(action)

4.注册监听器: subscribe(listener)

5.注销监听器,通过subscribe返回的函数

redux所在的应用只能有一个store实例,如果想将state操作分解成多个逻辑,只能将Reducer的代码分解为多个部分,以函数调用的方式提取出来处理各自的逻辑。

当我们已经有一个处理state的Reducer函数时,比如todoApp,创建store实例非常简单,只需将它传入createStore():

 import { createStore } from 'redux'
import todoApp from './reducers'
let store = createStore(todoApp)

createStore()可以接收第二个参数,作为state的初始值。文档中提到的一种情况是传入服务器返回的state作为初始state,实现定制化。

Dispatching Actions:

 //action creators
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(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()

一开始我以为store是一个独立且区别于reducer的对象,现在发现,原来createStore只是对Reducer做了一层包装。

当store.dispatch()方法被调用的时候,只需要传入action,其内部会自动获取即刻的state并一起传入Reducer中。

值得一提的是,subscribe()方法默认订阅的是state发生变化这个事件,和所有基于事件机制的方法一样,传入的是一个callback。其返回值默认是一个注销subscribe()的函数。