初识 Redux Store
现在我们可以开始了解如何将上面介绍的内容使用在 Redux 中了。
如你所见,如果你有一个 actions 集合,你可以调用 reduce
,获得最终的应用状态。当然,通常情况下不会如此,actions
将会在不同的时间发生:用户操作,远程调用,超时触发器等。
针对这些情况,我们可以使用 Redux Store。从名字可以看出它用来存储应用的状态。
Redux Store 通常会由一个 reducer 函数初始化,如我们之前实现的:
import {createStore} from 'redux';
const store = createStore(reducer);
接下来你就可以向这个 Store 指派 actions 了。Store 内部将会使用你实现的 reducer 来处理 action,并负责传递给
reducer 应用的 state,最后负责存储 reducer 返回的新 state:
store.dispatch({type: 'NEXT'});
任何时刻你都可以通过下面的方法获取当前的 state:
store.getState();
我们将会创建一个 store.js
用来初始化和导出一个 Redux Store 对象。让我们先写测试代码吧:
//test/store_spec.js
import {Map, fromJS} from 'immutable';
import {expect} from 'chai';
import makeStore from '../src/store';
describe('store', () => {
it('is a Redux store configured with the correct reducer', () => {
const store = makeStore();
expect(store.getState()).to.equal(Map());
store.dispatch({
type: 'SET_ENTRIES',
entries: ['Trainspotting', '28 Days Later']
});
expect(store.getState()).to.equal(fromJS({
entries: ['Trainspotting', '28 Days Later']
}));
});
});
在创建 Store 之前,我们先在项目中加入 Redux 库:
npm install --save redux
然后我们新建 store.js
文件,如下:
//src/store.js
import {createStore} from 'redux';
import reducer from './reducer';
export default function makeStore() {
return createStore(reducer);
}
Redux Store 负责将应用的所有组件关联起来:它持有应用的当前状态,并负责指派 actions,且负责调用包含了
业务逻辑的 reducer。
应用的业务代码和 Redux 的整合方式非常引人注目,因为我们只有一个普通的 reducer 函数,这是唯一需要告诉 Redux
的事儿。其它部分全部都是我们自己的,没有框架入侵的,高便携的纯函数代码!
现在我们创建一个应用的入口文件 index.js
:
//index.js
import makeStore from './src/store';
export const store = makeStore();
现在我们可以开启一个 Node REPL (例如 babel-node),
载入 index.js
文件来测试执行了。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论