企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 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使用。