dva
dva
- 基于
redux
、redux-saga
和react-router
的轻量级前端框架。(Inspired by elm and choo) - dva是基于react+redux最佳实践上实现的封装方案,简化了redux和redux-saga使用上的诸多繁琐操作
数据流向
- 数据的改变发生通常是通过:
- 用户交互行为(用户点击按钮等)
- 浏览器行为(如路由跳转等)触发的
- 当此类行为会改变数据的时候可以通过 dispatch 发起一个 action,如果是同步行为会直接通过 Reducers 改变 State ,如果是异步行为(副作用)会先触发 Effects 然后流向 Reducers 最终改变 State
8个概念
State
- State 表示 Model 的状态数据,通常表现为一个 javascript 对象(当然它可以是任何值);
- 操作的时候每次都要当作不可变数据(immutable data)来对待,保证每次都是全新对象,没有引用关系,这样才能保证 State 的独立性,便于测试和追踪变化。
Action
- Action 是一个普通 javascript 对象,它是改变 State 的唯一途径。
- 无论是从 UI 事件、网络回调,还是 WebSocket 等数据源所获得的数据,最终都会通过 dispatch 函数调用一个 action,从而改变对应的数据。
- action 必须带有 type 属性指明具体的行为,其它字段可以自定义,
- 如果要发起一个 action 需要使用 dispatch 函数;
- 需要注意的是 dispatch 是在组件 connect Models以后,通过 props 传入的。
dispatch
-
dispatching function 是一个用于触发 action 的函数
-
action 是改变 State 的唯一途径,但是它只描述了一个行为,而 dipatch 可以看作是触发这个行为的方式,而 Reducer 则是描述如何改变数据的。
-
在 dva 中,connect Model 的组件通过 props 可以访问到 dispatch,可以调用 Model 中的 Reducer 或者 Effects,常见的形式如:
dispatch({ type: 'user/add', // 如果在 model 外调用,需要添加 namespace payload: {}, // 需要传递的信息 });
Reducer
- Reducer(也称为 reducing function)函数接受两个参数:之前已经累积运算的结果和当前要被累积的值,返回的是一个新的累积结果。该函数把一个集合归并成一个单值。
- 在 dva 中,reducers 聚合积累的结果是当前 model 的 state 对象。
- 通过 actions 中传入的值,与当前 reducers 中的值进行运算获得新的值(也就是新的 state)。
- 需要注意的是 Reducer 必须是纯函数,所以同样的输入必然得到同样的输出,它们不应该产生任何副作用。
- 并且,每一次的计算都应该使用immutable data,这种特性简单理解就是每次操作都是返回一个全新的数据(独立,纯净),所以热重载和时间旅行这些功能才能够使用。
Effect
- Effect 被称为副作用,在我们的应用中,最常见的就是异步操作。
- 它来自于函数编程的概念,之所以叫副作用是因为它使得我们的函数变得不纯,同样的输入不一定获得同样的输出。
- dva 为了控制副作用的操作,底层引入了redux-sagas做异步流程控制,由于采用了generator的相关概念,所以将异步转成同步写法,从而将effects转为纯函数。
Subscription
- Subscriptions 是一种从 源 获取数据的方法,它来自于 elm。
- Subscription 语义是订阅,用于订阅一个数据源,然后根据条件 dispatch 需要的 action
- 数据源可以是当前的时间、服务器的 websocket 连接、keyboard 输入、geolocation 变化、history 路由变化等等。
Router
- 这里的路由通常指的是前端路由
- 由于我们的应用现在通常是单页应用,所以需要前端代码来控制路由逻辑
- 通过浏览器提供的 History API 可以监听浏览器url的变化,从而控制路由相关操作。
Route Components
- 在组件设计方法中,我们提到过 Container Components,在 dva 中我们通常将其约束为 Route Components
- 因为在 dva 中我们通常以页面维度来设计 Container Components。
- 所以在 dva 中,通常需要 connect Model的组件都是 Route Components,组织在/routes/目录下,而/components/目录下则是纯组件(Presentational Components)。
初始化环境
create-react-app dva-app
cd dva-app
cnpm i dva keymaster -S
文件结构
官方推荐的:
├── /mock/ # 数据mock的接口文件
├── /src/ # 项目源码目录
│ ├── /components/ # 项目组件
│ ├── /routes/ # 路由组件(页面维度)
│ ├── /models/ # 数据模型
│ ├── /services/ # 数据接口
│ ├── /utils/ # 工具函数
│ ├── route.js # 路由配置
│ ├── index.js # 入口文件
│ ├── index.less
│ └── index.html
├── package.json # 定义依赖的pkg文件
└── proxy.config.js # 数据mock配置文件
计数器
用法 | 说明 |
---|---|
app = dva(opts) | 创建应用,返回 dva 实例 |
app.use(hooks) | 配置 hooks 或者注册插件 |
app.model(model) | 注册 model |
app.router(({ history, app }) => RouterConfig) | 注册路由表 |
app.start(selector?) | 启动应用。selector 可选 |
import React from 'react';
import { Dispatch } from 'redux';
import dva, { connect } from 'dva';
import keymaster from 'keymaster';
import { RouterAPI } from 'dva';
import { Router, Route } from 'dva/router';
interface Counter1State {
number: 0
}
interface Counter2State {
number: 0
}
interface CombinedState {
counter1: Counter1State;
counter2: Counter2State;
}
const app = dva();
const delay = (millseconds: number) => {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve();
}, millseconds);
});
}
// 定义模型
app.model({
namespace: 'counter1',
state: { number: 0 },
reducers: {//接收老状态,返回新状态
add(state) { //dispatch({type:'add'});
return { number: state.number + 1 };
},
minus(state) {//dispatch({type:'minus'})
return { number: state.number - 1 };
}
},
// 延时操作 调用接口 等待
effects: {
*asyncAdd(action, { put, call }) { //redux-saga/effects {put,call}
yield call(delay, 1000);//把100传给delay并调用,yield会等待promise完成
yield put({ type: 'add' });
}
*log(action,{select}){
// 通过select可以拿到state
let state = yield select(state=>state.counter1)
console.log(state)
}
},
subscriptions: {
keyboard({ dispatch }) {
keymaster('space', () => {
dispatch({ type: 'add' });
});
},
changeTitle({ history }) {
setTimeout(function () {
history.listen(({ pathname }) => {
document.title = pathname;
});
}, 1000);
}
}
});
app.model({
namespace: 'counter2',
state: { number: 0 },
reducers: {//接收老状态,返回新状态
add(state) { //dispatch({type:'add'});
return { number: state.number + 1 };
},
minus(state) {//dispatch({type:'minus'})
return { number: state.number - 1 };
}
}
});
type Counter1Props = Counter1State & { dispatch: Dispatch };
const Counter1 = (props: Counter1Props) => {
return (
<div>
<p>{props.number}</p>
<button onClick={() => props.dispatch({ type: 'counter1/add' })}>add</button>
<button onClick={() => props.dispatch({ type: 'counter1/asyncAdd' })}>asyncAdd</button>
<button onClick={() => props.dispatch({ type: 'counter1/minus' })}>-</button>
</div>
)
}
type Counter2Props = Counter2State & { dispatch: Dispatch };
const Counter2 = (props: Counter2Props) => {
return (
<div>
<p>{props.number}</p>
<button onClick={() => props.dispatch({ type: 'counter2/add' })}>+</button>
<button onClick={() => props.dispatch({ type: 'counter2/minus' })}>-</button>
</div>
)
}
const mapStateToProps1 = (state: CombinedState): Counter1State => state.counter1;
const ConnectedCounter = connect(
mapStateToProps1
)(Counter1);
const mapStateToProps2 = (state: CombinedState): Counter2State => state.counter2;
const ConnectedCounter2 = connect(
mapStateToProps2
)(Counter2);
app.router(
(api?: RouterAPI) => {
let { history } = api!;
return (
(
<Router history={history}>
<>
<Route path="/counter1" component={ConnectedCounter} />
<Route path="/counter2" component={ConnectedCounter2} />
</>
</Router>
)
)
}
);
app.start('#root');
- namespace model 的命名空间,同时也是他在全局 state 上的属性,只能用字符串
- state 初始值
- reducers 以 key/value 格式定义 reducer。用于处理同步操作,唯一可以修改 state 的地方。由 action 触发。
- effects 以 key/value 格式定义 effect。用于处理异步操作和业务逻辑,不直接修改 state。由 action 触发,可以触发 action,可以和服务器交互,可以获取全局 state 的数据等等。
- subscriptions 以 key/value 格式定义 subscription。subscription 是订阅,用于订阅一个数据源,然后根据需要 dispatch 相应的 action。在 app.start() 时被执行,数据源可以是当前的时间、服务器的 websocket 连接、keyboard 输入、geolocation 变化、history 路由变化等等。
基本计数器
基本计数器
使用
index.tsx
import React from 'react';
import dva, { connect } from './dva';
const app = dva();
app.model({
namespace: 'counter',
state: { number: 0 },
reducers: {
add(state) {
return { number: state.number + 1 };
}
}
});
function Counter(props) {
return (
<div>
<p>{props.number}</p>
<button onClick={() => props.dispatch({ type: "counter/add" })}>+</button>
</div>
)
}
const ConnectedCounter = connect(
(state) => state.counter
)(Counter);
app.router(() => <ConnectedCounter />);
app.start('#root');
实现
dva\index.tsx
src\dva\index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, combineReducers } from 'redux';
import { connect, Provider } from 'react-redux';
import { DvaInstance, Router, Model } from './typings';
import prefixNamespace from './prefixNamespace';
export { connect };
export default function () {
const app: DvaInstance = {
_models: [],
model,
router,
_router: null,
start
}
const initialReducers = {};
function model(model: Model) {
const prefixedModel = prefixNamespace(model);
app._models.push(prefixedModel);
return prefixedModel;
}
function router(router: Router) {
app._router = router;
}
function start(root) {
for (const model of app._models) {
initialReducers[model.namespace] = getReducer(model);
}
let rootReducer = createReducer();
let store = createStore(rootReducer);
ReactDOM.render(<Provider store={store}>{app._router()}</Provider>, document.querySelector(root));
function createReducer() {
return combineReducers(initialReducers);
}
}
return app;
}
function getReducer(model) {
let { reducers, state: defaultState } = model;
let reducer = (state = defaultState, action) => {
let reducer = reducers[action.type];
if (reducer) {
return reducer(state, action);
}
return state;
}
return reducer;
}
export * from './typings';
prefixNamespace.tsx
src\dva\prefixNamespace.tsx
import { NAMESPACE_SEP } from './constants';
function prefix(obj, namespace) {
return Object.keys(obj).reduce((memo, key) => {
const newKey = `${namespace}${NAMESPACE_SEP}${key}`;
memo[newKey] = obj[key];
return memo;
}, {});
}
export default function prefixNamespace(model) {
if (model.reducers)
model.reducers = prefix(model.reducers, model.namespace);
return model;
}
constants.tsx
src\dva\constants.tsx
export const NAMESPACE_SEP = '/';
typings.tsx
src\dva\typings.tsx
import { Dispatch, Reducer, AnyAction, MiddlewareAPI, StoreEnhancer } from 'redux';
import { History } from 'history';
export interface ReducersMapObject {
[key: string]: Reducer<any>;
}
export interface ReducerEnhancer {
(reducer: Reducer<any>): void,
}
export interface EffectsCommandMap {
put: <A extends AnyAction>(action: A) => any,
call: Function,
select: Function,
take: Function,
cancel: Function,
[key: string]: any,
}
export type EffectType = 'takeEvery' | 'takeLatest' | 'watcher' | 'throttle';
export type EffectWithType = [Effect, { type: EffectType }];
export type Effect = (action: AnyAction, effects: EffectsCommandMap) => void;
export type ReducersMapObjectWithEnhancer = [ReducersMapObject, ReducerEnhancer];
export interface EffectsMapObject {
[key: string]: Effect | EffectWithType,
}
export interface SubscriptionsMapObject {
[key: string]: Subscription,
}
export interface SubscriptionAPI {
history: History,
dispatch: Dispatch<any>,
}
export type Subscription = (api: SubscriptionAPI, done: Function) => void;
export interface Model {
namespace: string,
state?: any,
reducers?: ReducersMapObject | ReducersMapObjectWithEnhancer,
effects?: EffectsMapObject,
subscriptions?: SubscriptionsMapObject,
}
export interface RouterAPI {
history: History,
app: DvaInstance,
}
export interface Router {
(api?: RouterAPI): JSX.Element | Object,
}
export interface onActionFunc {
(api: MiddlewareAPI<any>): void,
}
export interface Hooks {
onError?: (e: Error, dispatch: Dispatch<any>) => void,
onAction?: onActionFunc | onActionFunc[],
onStateChange?: () => void,
onReducer?: ReducerEnhancer,
onEffect?: () => void,
onHmr?: () => void,
extraReducers?: ReducersMapObject,
extraEnhancers?: StoreEnhancer<any>[],
}
export interface DvaInstance extends Record<any, any> {
//use: (hooks: Hooks) => void,
model: (model: Model) => void,
//unmodel: (namespace: string) => void,
router: (router: Router) => void,
start: (selector?: HTMLElement | string) => any,
}
支持effects
使用
index.tsx
import React from 'react';
import dva, { connect } from './dva';
const app = dva();
app.model({
namespace: 'counter',
state: { number: 0 },
reducers: {
add(state) {
return { number: state.number + 1 };
}
},
+ effects: {
+ *asyncAdd(action, { call, put }) {
+ yield call(delay, 1000);
+ yield put({ type: 'counter/add' });
+ }
+ }
});
function Counter(props) {
return (
<div>
<p>{props.number}</p>
<button onClick={() => props.dispatch({ type: "counter/add" })}>加1</button>
+ <button onClick={() => props.dispatch({ type: "counter/asyncAdd" })}>异步+</button>
</div>
)
}
const ConnectedCounter = connect(
(state) => state.counter
)(Counter);
app.router(() => <ConnectedCounter />);
app.start('#root');
+function delay(ms) {
+ return new Promise((resolve) => {
+ setTimeout(function () {
+ resolve();
+ }, ms);
+ });
+}
实现
dva\index.tsx
src\dva\index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
+import { createStore, combineReducers, applyMiddleware } from 'redux';
+import createSagaMiddleware from 'redux-saga';
+import * as sagaEffects from 'redux-saga/effects';
+import { NAMESPACE_SEP } from './constants';
import { connect, Provider } from 'react-redux';
import { DvaInstance, Router, Model } from './typings';
import prefixNamespace from './prefixNamespace';
export { connect };
export default function () {
const app: DvaInstance = {
_models: [],
model,
router,
_router: null,
start
}
const initialReducers = {};
function model(model: Model) {
const prefixedModel = prefixNamespace(model);
app._models.push(prefixedModel);
return prefixedModel;
}
function router(router: Router) {
app._router = router;
}
function start(root) {
for (const model of app._models) {
initialReducers[model.namespace] = getReducer(model);
}
let rootReducer = createReducer();
+ const sagas = getSagas(app);
+ const sagaMiddleware = createSagaMiddleware();
+ let store = createStore(rootReducer, applyMiddleware(sagaMiddleware));
+ sagas.forEach(saga => sagaMiddleware.run(saga));
+ ReactDOM.render(<Provider store={store}>{app._router()}</Provider>, document.querySelector(root));
function createReducer() {
return combineReducers(initialReducers);
}
}
+ function getSagas(app) {
+ let sagas: Array<any> = [];
+ for (const model of app._models) {
+ sagas.push(getSaga(model.effects, model));
+ }
+ return sagas;
+ }
return app;
}
+function getSaga(effects, model) {
+ return function* () {
+ for (const key in effects) {
+ const watcher = getWatcher(key, model.effects[key], model);
+ yield sagaEffects.fork(watcher);
+ }
+ };
+}
+function getWatcher(key, effect, model) {
+ return function* () {
+ yield sagaEffects.takeEvery(key, function* sagaWithCatch(...args) {
+ yield effect(...args, { ...sagaEffects, put: action => sagaEffects.put({ ...action, type: prefixType(action.type, model) }) });
+ });
+ };
+}
+function prefixType(type, model) {
+ if (type.indexOf('/') === -1) {
+ return `${model.namespace}${NAMESPACE_SEP}${type}`;
+ }
+ return type;
+}
function getReducer(model) {
let { reducers, state: defaultState } = model;
let reducer = (state = defaultState, action) => {
let reducer = reducers[action.type];
if (reducer) {
return reducer(state, action);
}
return state;
}
return reducer;
}
prefixNamespace.tsx
src\dva\prefixNamespace.tsx
import { NAMESPACE_SEP } from './constants';
function prefix(obj, namespace) {
return Object.keys(obj).reduce((memo, key) => {
const newKey = `${namespace}${NAMESPACE_SEP}${key}`;
memo[newKey] = obj[key];
return memo;
}, {});
}
export default function prefixNamespace(model) {
if (model.reducers)
model.reducers = prefix(model.reducers, model.namespace);
+ if (model.effects) {
+ model.effects = prefix(model.effects, model.namespace);
+ }
return model;
}
支持路由
使用
index.tsx
import React from 'react';
import dva, { connect } from './dva';
+import { Router, Route } from './dva/router';
const app = dva();
app.model({
namespace: 'counter',
state: { number: 0 },
reducers: {
add(state) {
return { number: state.number + 1 };
}
},
effects: {
*asyncAdd(action, { call, put }) {
yield call(delay, 1000);
yield put({ type: 'counter/add' });
}
}
});
function Counter(props) {
return (
<div>
<p>{props.number}</p>
<button onClick={() => props.dispatch({ type: "counter/add" })}>加1</button>
<button onClick={() => props.dispatch({ type: "counter/asyncAdd" })}>异步+</button>
</div>
)
}
const ConnectedCounter = connect(
(state) => state.counter
)(Counter);
const Home = () => <div>Home</div>
+app.router((api: any) => (
+ <Router history={api.history}>
+ <>
+ <Route path="/" exact={true} component={Home} />
+ <Route path="/counter" component={ConnectedCounter} />
+ </>
+ </Router>
+));
app.start('#root');
function delay(ms) {
return new Promise((resolve) => {
setTimeout(function () {
resolve();
}, ms);
});
}
实现
dva\index.tsx
src\dva\index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import * as sagaEffects from 'redux-saga/effects';
import { NAMESPACE_SEP } from './constants';
import { connect, Provider } from 'react-redux';
import { DvaInstance, Router, Model } from './typings';
import prefixNamespace from './prefixNamespace';
+import { createHashHistory } from 'history';
+let history = createHashHistory();
export { connect };
export default function () {
const app: DvaInstance = {
_models: [],
model,
router,
_router: null,
start
}
const initialReducers = {};
function model(model: Model) {
const prefixedModel = prefixNamespace(model);
app._models.push(prefixedModel);
return prefixedModel;
}
function router(router: Router) {
app._router = router;
}
function start(root) {
for (const model of app._models) {
initialReducers[model.namespace] = getReducer(model);
}
let rootReducer = createReducer();
const sagas = getSagas(app);
const sagaMiddleware = createSagaMiddleware();
let store = createStore(rootReducer, applyMiddleware(sagaMiddleware));
sagas.forEach(saga => sagaMiddleware.run(saga));
+ ReactDOM.render(<Provider store={store}>{app._router({ history })}</Provider>, document.querySelector(root))
function createReducer() {
return combineReducers(initialReducers);
}
}
function getSagas(app) {
let sagas: Array<any> = [];
for (const model of app._models) {
sagas.push(getSaga(model.effects, model));
}
return sagas;
}
return app;
}
function getSaga(effects, model) {
return function* () {
for (const key in effects) {
const watcher = getWatcher(key, model.effects[key], model);
yield sagaEffects.fork(watcher);
}
};
}
function getWatcher(key, effect, model) {
return function* () {
yield sagaEffects.takeEvery(key, function* sagaWithCatch(...args) {
yield effect(...args, { ...sagaEffects, put: action => sagaEffects.put({ ...action, type: prefixType(action.type, model) }) });
});
};
}
function prefixType(type, model) {
if (type.indexOf('/') === -1) {
return `${model.namespace}${NAMESPACE_SEP}${type}`;
}
return type;
}
function getReducer(model) {
let { reducers, state: defaultState } = model;
let reducer = (state = defaultState, action) => {
let reducer = reducers[action.type];
if (reducer) {
return reducer(state, action);
}
return state;
}
return reducer;
}
export * from './typings';
router.tsx
src\dva\router.tsx
export * from 'react-router-dom';
跳转路径
使用
index.tsx
import React from 'react';
import dva, { connect } from './dva';
+import { Router, Route, routerRedux } from './dva/router';
+import { ConnectedRouter } from 'connected-react-router';
const app = dva();
app.model({
namespace: 'counter',
state: { number: 0 },
reducers: {
add(state) {
return { number: state.number + 1 };
}
},
effects: {
*asyncAdd(action, { call, put }) {
yield call(delay, 1000);
yield put({ type: 'counter/add' });
},
+ *goto({ to }, { put }) {
+ yield put(routerRedux.push(to));
+ }
}
});
function Counter(props) {
return (
<div>
<p>{props.number}</p>
<button onClick={() => props.dispatch({ type: "counter/add" })}>加1</button>
<button onClick={() => props.dispatch({ type: "counter/asyncAdd" })}>异步+</button>
+ <button onClick={() => props.dispatch({ type: "counter/goto", to: '/' })}>跳转到/</button>
</div>
)
}
const ConnectedCounter = connect(
(state) => state.counter
)(Counter);
const Home = () => <div>Home</div>
app.router((api: any) => (
+ <ConnectedRouter history={api.history}>
<>
<Route path="/" exact={true} component={Home} />
<Route path="/counter" component={ConnectedCounter} />
</>
+ </ConnectedRouter>
));
app.start('#root');
function delay(ms) {
return new Promise((resolve) => {
setTimeout(function () {
resolve();
}, ms);
});
}
实现
dva\index.tsx
src\dva\index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import * as sagaEffects from 'redux-saga/effects';
import { NAMESPACE_SEP } from './constants';
import { connect, Provider } from 'react-redux';
import { DvaInstance, Router, Model } from './typings';
import prefixNamespace from './prefixNamespace';
import { createHashHistory } from 'history';
+import { routerMiddleware, connectRouter, ConnectedRouter } from "connected-react-router";
let history = createHashHistory();
export { connect };
export default function () {
const app: DvaInstance = {
_models: [],
model,
router,
_router: null,
start
}
+ const initialReducers = { router: connectRouter(history) };
function model(model: Model) {
const prefixedModel = prefixNamespace(model);
app._models.push(prefixedModel);
return prefixedModel;
}
function router(router: Router) {
app._router = router;
}
function start(root) {
for (const model of app._models) {
initialReducers[model.namespace] = getReducer(model);
}
let rootReducer = createReducer();
const sagas = getSagas(app);
const sagaMiddleware = createSagaMiddleware();
+ let store = createStore(rootReducer, applyMiddleware(routerMiddleware(history), sagaMiddleware));
sagas.forEach(saga => sagaMiddleware.run(saga));
ReactDOM.render(<Provider store={store}>{app._router({ history })}</Provider>, document.querySelector(root));
function createReducer() {
return combineReducers(initialReducers);
}
}
function getSagas(app) {
let sagas: Array<any> = [];
for (const model of app._models) {
sagas.push(getSaga(model.effects, model));
}
return sagas;
}
return app;
}
function getSaga(effects, model) {
return function* () {
for (const key in effects) {
const watcher = getWatcher(key, model.effects[key], model);
yield sagaEffects.fork(watcher);
}
};
}
function getWatcher(key, effect, model) {
return function* () {
yield sagaEffects.takeEvery(key, function* sagaWithCatch(...args) {
yield effect(...args, { ...sagaEffects, put: action => sagaEffects.put({ ...action, type: prefixType(action.type, model) }) });
});
};
}
function prefixType(type, model) {
if (type.indexOf('/') === -1) {
return `${model.namespace}${NAMESPACE_SEP}${type}`;
}
return type;
}
function getReducer(model) {
let { reducers, state: defaultState } = model;
let reducer = (state = defaultState, action) => {
let reducer = reducers[action.type];
if (reducer) {
return reducer(state, action);
}
return state;
}
return reducer;
}
export * from './typings';
src\dva\router.tsx
src\dva\router.tsx
import * as routerRedux from 'connected-react-router';
export * from 'react-router-dom';
export {
routerRedux
}
dva-loading
- Auto loading data binding plugin for dva. You don’t need to write showLoading and hideLoading any more.
- dva-loading
使用
index.tsx
import React from 'react';
import dva, { connect } from './dva';
import { Router, Route, routerRedux } from './dva/router';
import { ConnectedRouter } from 'connected-react-router';
+import createLoading from './dva-loading';
const app = dva();
+app.use(createLoading());
app.model({
namespace: 'counter',
state: { number: 0 },
reducers: {
add(state) {
return { number: state.number + 1 };
}
},
effects: {
*asyncAdd(action, { call, put }) {
yield call(delay, 1000);
yield put({ type: 'counter/add' });
},
*goto({ to }, { put }) {
yield put(routerRedux.push(to));
}
}
});
function Counter(props) {
return (
<div>
+ <p> {props.loading.models.counter ? 'loading' : props.counter.number}</p>
<button onClick={() => props.dispatch({ type: "counter/add" })}>加1</button>
<button onClick={() => props.dispatch({ type: "counter/asyncAdd" })}>异步+</button>
<button onClick={() => props.dispatch({ type: "counter/goto", to: '/' })}>跳转到/</button>
</div>
)
}
const ConnectedCounter = connect(
+ (state) => state
)(Counter);
const Home = () => <div>Home</div>
app.router((api: any) => (
+ <Router history={api.history}>
<>
<Route path="/" exact={true} component={Home} />
<Route path="/counter" component={ConnectedCounter} />
</>
+ </Router>
));
app.start('#root');
function delay(ms) {
return new Promise((resolve) => {
setTimeout(function () {
resolve();
}, ms);
});
}
实现
dva\index.tsx
src\dva\index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import * as sagaEffects from 'redux-saga/effects';
import { NAMESPACE_SEP } from './constants';
import { connect, Provider } from 'react-redux';
import { DvaInstance, Router, Model } from './typings';
import prefixNamespace from './prefixNamespace';
import { createHashHistory } from 'history';
+import Plugin, { filterHooks } from './plugin';
import { routerMiddleware, connectRouter, ConnectedRouter } from "connected-react-router";
let history = createHashHistory();
export { connect };
+export default function (opts = {}) {
const app: DvaInstance = {
_models: [],
model,
router,
_router: null,
start
}
const initialReducers = { router: connectRouter(history) };
function model(model: Model) {
const prefixedModel = prefixNamespace(model);
app._models.push(prefixedModel);
return prefixedModel;
}
function router(router: Router) {
app._router = router;
}
+ const plugin = new Plugin();
+ plugin.use(filterHooks(opts));
+ app.use = plugin.use.bind(plugin);
function start(root) {
for (const model of app._models) {
initialReducers[model.namespace] = getReducer(model);
}
let rootReducer = createReducer();
const sagas = getSagas(app);
const sagaMiddleware = createSagaMiddleware();
let store = createStore(rootReducer, applyMiddleware(routerMiddleware(history), sagaMiddleware));
sagas.forEach(saga => sagaMiddleware.run(saga));
ReactDOM.render(<Provider store={store}>{app._router({ history })}</Provider>, document.querySelector(root));
function createReducer() {
+ const extraReducers = plugin.get('extraReducers');
+ return combineReducers({
+ ...initialReducers,
+ ...extraReducers
+ });
}
}
function getSagas(app) {
let sagas: Array<any> = [];
for (const model of app._models) {
+ sagas.push(getSaga(model.effects, model, plugin.get('onEffect')));
}
return sagas;
}
return app;
}
+function getSaga(effects, model, onEffect) {
return function* () {
for (const key in effects) {
+ const watcher = getWatcher(key, model.effects[key], model, onEffect);
yield sagaEffects.fork(watcher);
}
};
}
+function getWatcher(key, effect, model, onEffect) {
return function* () {
yield sagaEffects.takeEvery(key, function* sagaWithCatch(...args) {
+ if (onEffect) {
+ for (const fn of onEffect) {
+ effect = fn(effect, sagaEffects, model, key);
+ }
+ }
yield effect(...args, { ...sagaEffects, put: action => sagaEffects.put({ ...action, type: prefixType(action.type, model) }) });
});
};
}
function prefixType(type, model) {
if (type.indexOf('/') === -1) {
return `${model.namespace}${NAMESPACE_SEP}${type}`;
}
return type;
}
function getReducer(model) {
let { reducers, state: defaultState } = model;
let reducer = (state = defaultState, action) => {
let reducer = reducers[action.type];
if (reducer) {
return reducer(state, action);
}
return state;
}
return reducer;
}
export * from './typings';
dva-loading.tsx
src\dva-loading.tsx
const SHOW = '@@DVA_LOADING/SHOW';
const HIDE = '@@DVA_LOADING/HIDE';
const NAMESPACE = 'loading';
function createLoading(opts: any = {}) {
const initialState = {
global: false,
models: {},
effects: {},
};
const extraReducers = {
[NAMESPACE](state = initialState, { type, payload }) {
const { namespace, actionType } = payload || {};
let ret;
switch (type) {
case SHOW:
ret = {
...state,
global: true,
models: { ...state.models, [namespace]: true },
effects: { ...state.effects, [actionType]: true },
};
break;
case HIDE: {
const effects = { ...state.effects, [actionType]: false };
const models = {
...state.models,
[namespace]: Object.keys(effects).some(actionType => {
const _namespace = actionType.split('/')[0];
if (_namespace !== namespace) return false;
return effects[actionType];
}),
};
const global = Object.keys(models).some(namespace => {
return models[namespace];
});
ret = {
...state,
global,
models,
effects,
};
break;
}
default:
ret = state;
break;
}
return ret;
},
};
function onEffect(effect, { put }, model, actionType) {
const { namespace } = model;
return function* (...args) {
yield put({ type: SHOW, payload: { namespace, actionType } });
try {
yield effect(...args);
} finally {
yield put({ type: HIDE, payload: { namespace, actionType } });
}
};
}
return {
extraReducers,
onEffect,
};
}
export default createLoading;
plugin.tsx
src\dva\plugin.tsx
const hooks = [
'onEffect',
'extraReducers'
];
export function filterHooks(obj) {
return Object.keys(obj).reduce((memo, key) => {
if (hooks.indexOf(key) > -1) {
memo[key] = obj[key];
}
return memo;
}, {});
}
export default class Plugin {
hooks: any
constructor() {
this.hooks = hooks.reduce((memo, key) => {
memo[key] = [];
return memo;
}, {});
}
use(plugin) {
const { hooks } = this;
for (const key in plugin) {
hooks[key].push(plugin[key]);
}
}
get(key) {
const { hooks } = this;
if (key === 'extraReducers') {
return getExtraReducers(hooks[key]);
} else {
return hooks[key];
}
}
}
function getExtraReducers(hook) {
let ret = {};
for (const reducerObj of hook) {
ret = { ...ret, ...reducerObj };
}
return ret;
}
dynamic
import React from 'react';
import dva, { connect } from './dva';
+import { Router, Route, routerRedux, Link } from './dva/router';
import { ConnectedRouter } from 'connected-react-router';
import createLoading from './dva-loading';
+import dynamic from './dva/dynamic';
const app = dva();
app.use(createLoading());
app.model({
namespace: 'counter',
state: { number: 0 },
reducers: {
add(state) {
return { number: state.number + 1 };
}
},
effects: {
*asyncAdd(action, { call, put }) {
yield call(delay, 1000);
yield put({ type: 'counter/add' });
},
*goto({ to }, { put }) {
yield put(routerRedux.push(to));
}
}
});
function Counter(props) {
return (
<div>
<p> {props.loading.models.counter ? 'loading' : props.counter.number}</p>
<button onClick={() => props.dispatch({ type: "counter/add" })}>加1</button>
<button onClick={() => props.dispatch({ type: "counter/asyncAdd" })}>异步+</button>
<button onClick={() => props.dispatch({ type: "counter/goto", to: '/' })}>跳转到/</button>
</div>
)
}
const ConnectedCounter = connect(
(state) => state
)(Counter);
+const Home = () => <div>Home</div>;
+const UserPageComponent = (dynamic as any)({
+ app,
+ models: () => [
+ import('./models/users'),
+ ],
+ component: () => import('./routes/UserPage'),
+});
app.router((api: any) => (
<Router history={api.history}>
<>
+ <ul>
+ <li><Link to="/">Home</Link></li>
+ <li><Link to="/counter">counter</Link></li>
+ <li><Link to="/users">users</Link></li>
+ </ul>
<Route path="/" exact={true} component={Home} />
<Route path="/counter" component={ConnectedCounter} />
+ <Route path="/users" component={UserPageComponent} />
</>
</Router>
));
app.start('#root');
function delay(ms) {
return new Promise((resolve) => {
setTimeout(function () {
resolve();
}, ms);
});
}
实现
dva\index.tsx
src\dva\index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import * as sagaEffects from 'redux-saga/effects';
import { NAMESPACE_SEP } from './constants';
import { connect, Provider } from 'react-redux';
import { DvaInstance, Router, Model } from './typings';
import prefixNamespace from './prefixNamespace';
import { createHashHistory } from 'history';
import Plugin, { filterHooks } from './plugin';
import { routerMiddleware, connectRouter, ConnectedRouter } from "connected-react-router";
let history = createHashHistory();
export { connect };
export default function (opts = {}) {
const app: DvaInstance = {
_models: [],
model,
router,
_router: null,
start
}
const initialReducers = { router: connectRouter(history) };
function model(model: Model) {
const prefixedModel = prefixNamespace(model);
app._models.push(prefixedModel);
return prefixedModel;
}
function router(router: Router) {
app._router = router;
}
const plugin = new Plugin();
plugin.use(filterHooks(opts));
app.use = plugin.use.bind(plugin);
function start(root) {
for (const model of app._models) {
initialReducers[model.namespace] = getReducer(model);
}
let rootReducer = createReducer();
const sagas = getSagas(app);
const sagaMiddleware = createSagaMiddleware();
let store = createStore(rootReducer, applyMiddleware(routerMiddleware(history), sagaMiddleware));
sagas.forEach(saga => sagaMiddleware.run(saga));
ReactDOM.render(<Provider store={store}>{app._router({ history })}</Provider>, document.querySelector(root))
+ app.model = injectModel.bind(app);
+ app._getSaga = getSaga;
+ function injectModel(m) {
+ m = model(m);
+ initialReducers[m.namespace] = getReducer(m);
+ store.replaceReducer(createReducer());
+ if (m.effects) {
+ sagaMiddleware.run(app._getSaga(m.effects, m));
+ }
+ if (m.subscriptions) {
+ runSubscription(m.subscriptions, m, app);
+ }
+ }
+ function runSubscription(subscriptions, model, app) {
+ for (const key in subscriptions) {
+ subscriptions[key](
+ {
+ dispatch: prefixedDispatch(store.dispatch, model),
+ history: app._history,
+ }
+ );
+ }
+ }
+ function prefixedDispatch(dispatch, model) {
+ return action => {
+ const { type } = action;
+ return dispatch({ ...action, type: prefixType(type, model) });
+ };
+ }
function createReducer() {
const extraReducers = plugin.get('extraReducers');
return combineReducers({
...initialReducers,
...extraReducers
});
}
+ }
function getSagas(app) {
let sagas: Array<any> = [];
for (const model of app._models) {
sagas.push(getSaga(model.effects, model, plugin.get('onEffect')));
}
return sagas;
}
return app;
}
function getSaga(effects, model, onEffect) {
return function* () {
for (const key in effects) {
const watcher = getWatcher(key, model.effects[key], model, onEffect);
yield sagaEffects.fork(watcher);
}
};
}
function getWatcher(key, effect, model, onEffect) {
return function* () {
yield sagaEffects.takeEvery(key, function* sagaWithCatch(...args) {
if (onEffect) {
for (const fn of onEffect) {
effect = fn(effect, sagaEffects, model, key);
}
}
yield effect(...args, { ...sagaEffects, put: action => sagaEffects.put({ ...action, type: prefixType(action.type, model) }) });
});
};
}
function prefixType(type, model) {
if (type.indexOf('/') === -1) {
return `${model.namespace}${NAMESPACE_SEP}${type}`;
}
return type;
}
function getReducer(model) {
let { reducers = {}, state: defaultState } = model;
+ return (state = defaultState, action) => {
let reducer = reducers[action.type];
if (reducer) {
return reducer(state, action);
}
return state;
}
}
export * from './typings';
dynamic.tsx
src\dva\dynamic.tsx
import React, { Component, JSXElementConstructor } from 'react';
let defaultLoadingComponent = () => <div>loading</div>;
export default function dynamic(config) {
const { app, models, component } = config;
return class DynamicComponent extends Component<any, any> {
LoadingComponent: any = null
constructor(props) {
super(props);
this.LoadingComponent = config.LoadingComponent || defaultLoadingComponent;
let AsyncComponent: JSXElementConstructor<any> | null = null;
this.state = { AsyncComponent };
}
componentDidMount() {
Promise.all([Promise.all(models()), component()]).then(([models, component]) => {
let resolveModels = models.map((model) => (model as any).default);
resolveModels.forEach(model => {
app.model(model);
});
let AsyncComponent = component.default || component;
this.setState({ AsyncComponent });
});
}
render() {
const { AsyncComponent } = this.state;
const { LoadingComponent } = this;
if (AsyncComponent)
return <AsyncComponent {...this.props} />;
return <LoadingComponent {...this.props} />;
}
};
}
src\models\users.tsx
src\models\users.tsx
function delay(ms) {
return new Promise((resolve) => {
setTimeout(function () {
resolve();
}, ms);
});
}
export default {
namespace: 'users',
state: { list: [{ id: 1, name: '珠峰' }, { id: 2, name: '架构' }] },
reducers: {
add(state, action) {
return { list: [...state.list, { id: Date.now(), name: action.payload }] };
}
},
effects: {
*asyncAdd(action, { call, put }) {
yield call(delay, 1000);
yield put({ type: 'add', payload: '学院' });
}
}
}
routes\UserPage.tsx
src\routes\UserPage.tsx
import React from 'react';
import { connect } from "../dva";
function UserPage(props) {
let list = props.list || [];
return (
<>
<button onClick={() => props.dispatch({ type: 'users/asyncAdd' })}>+</button>
<ul>
{
list.map(user => (
<li key={user.id}>{user.name}</li>
))
}
</ul>
</>
)
}
export default connect(state => state.users)(UserPage);
onAction中间件
cnpm i redux-logger -S
使用
index.tsx
import React from 'react';
import dva, { connect } from './dva';
import { Router, Route, routerRedux, Link } from './dva/router';
import createLoading from './dva-loading';
import dynamic from './dva/dynamic';
+import { createLogger } from './redux-logger';
const app = dva();
+app.use({ onAction: createLogger() });
app.use(createLoading());
app.model({
namespace: 'counter',
state: { number: 0 },
reducers: {
add(state) {
return { number: state.number + 1 };
}
},
effects: {
*asyncAdd(action, { call, put }) {
yield call(delay, 1000);
yield put({ type: 'counter/add' });
},
*goto({ to }, { put }) {
yield put(routerRedux.push(to));
}
}
});
function Counter(props) {
return (
<div>
<p> {props.loading.models.counter ? 'loading' : props.counter.number}</p>
<button onClick={() => props.dispatch({ type: "counter/add" })}>加1</button>
<button onClick={() => props.dispatch({ type: "counter/asyncAdd" })}>异步+</button>
<button onClick={() => props.dispatch({ type: "counter/goto", to: '/' })}>跳转到/</button>
</div>
)
}
const ConnectedCounter = connect(
(state) => state
)(Counter);
const Home = () => <div>Home</div>;
const UserPageComponent = (dynamic as any)({
app,
models: () => [
import('./models/users'),
],
component: () => import('./routes/UserPage'),
});
app.router((api: any) => (
<Router history={api.history}>
<>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/counter">counter</Link></li>
<li><Link to="/users">users</Link></li>
</ul>
<Route path="/" exact={true} component={Home} />
<Route path="/counter" component={ConnectedCounter} />
<Route path="/users" component={UserPageComponent} />
</>
</Router>
));
app.start('#root');
function delay(ms) {
return new Promise((resolve) => {
setTimeout(function () {
resolve();
}, ms);
});
}
实现
dva\index.tsx
src\dva\index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import * as sagaEffects from 'redux-saga/effects';
import { NAMESPACE_SEP } from './constants';
import { connect, Provider } from 'react-redux';
import { DvaInstance, Router, Model } from './typings';
import prefixNamespace from './prefixNamespace';
import { createHashHistory } from 'history';
import Plugin, { filterHooks } from './plugin';
import { routerMiddleware, connectRouter } from "connected-react-router";
let history = createHashHistory();
export { connect };
export default function (opts = {}) {
const app: DvaInstance = {
_models: [],
model,
router,
_router: null,
start
}
const initialReducers = { router: connectRouter(history) };
function model(model: Model) {
const prefixedModel = prefixNamespace(model);
app._models.push(prefixedModel);
return prefixedModel;
}
function router(router: Router) {
app._router = router;
}
const plugin = new Plugin();
plugin.use(filterHooks(opts));
app.use = plugin.use.bind(plugin);
function start(root) {
for (const model of app._models) {
initialReducers[model.namespace] = getReducer(model);
}
let rootReducer = createReducer();
const sagas = getSagas(app);
const sagaMiddleware = createSagaMiddleware();
+ const extraMiddlewares = plugin.get('onAction');
+ let store = createStore(rootReducer, applyMiddleware(...extraMiddlewares, routerMiddleware(history), sagaMiddleware));
sagas.forEach(saga => sagaMiddleware.run(saga));
ReactDOM.render(<Provider store={store}>{app._router({ history })}</Provider>, document.querySelector(root))
app.model = injectModel.bind(app);
app._getSaga = getSaga;
function injectModel(m) {
m = model(m);
initialReducers[m.namespace] = getReducer(m);
store.replaceReducer(createReducer());
if (m.effects) {
sagaMiddleware.run(app._getSaga(m.effects, m));
}
if (m.subscriptions) {
runSubscription(m.subscriptions, m, app);
}
}
function runSubscription(subscriptions, model, app) {
for (const key in subscriptions) {
subscriptions[key](
{
dispatch: prefixedDispatch(store.dispatch, model),
history: app._history,
}
);
}
}
function prefixedDispatch(dispatch, model) {
return action => {
const { type } = action;
return dispatch({ ...action, type: prefixType(type, model) });
};
}
function createReducer() {
const extraReducers = plugin.get('extraReducers');
return combineReducers({
...initialReducers,
...extraReducers
});
}
}
function getSagas(app) {
let sagas: Array<any> = [];
for (const model of app._models) {
sagas.push(getSaga(model.effects, model, plugin.get('onEffect')));
}
return sagas;
}
return app;
}
function getSaga(effects, model, onEffect) {
return function* () {
for (const key in effects) {
const watcher = getWatcher(key, model.effects[key], model, onEffect);
yield sagaEffects.fork(watcher);
}
};
}
function getWatcher(key, effect, model, onEffect) {
return function* () {
yield sagaEffects.takeEvery(key, function* sagaWithCatch(...args) {
if (onEffect) {
for (const fn of onEffect) {
effect = fn(effect, sagaEffects, model, key);
}
}
yield effect(...args, { ...sagaEffects, put: action => sagaEffects.put({ ...action, type: prefixType(action.type, model) }) });
});
};
}
function prefixType(type, model) {
if (type.indexOf('/') === -1) {
return `${model.namespace}${NAMESPACE_SEP}${type}`;
}
return type;
}
function getReducer(model) {
let { reducers = {}, state: defaultState } = model;
return (state = defaultState, action) => {
let reducer = reducers[action.type];
if (reducer) {
return reducer(state, action);
}
return state;
}
}
export * from './typings';
src\dva\plugin.tsx
src\dva\plugin.tsx
const hooks = [
'onEffect',
'extraReducers',
+ 'onAction'
];
export function filterHooks(obj) {
return Object.keys(obj).reduce((memo, key) => {
if (hooks.indexOf(key) > -1) {
memo[key] = obj[key];
}
return memo;
}, {});
}
export default class Plugin {
hooks: any
constructor() {
this.hooks = hooks.reduce((memo, key) => {
memo[key] = [];
return memo;
}, {});
}
use(plugin) {
const { hooks } = this;
for (const key in plugin) {
hooks[key].push(plugin[key]);
}
}
get(key) {
const { hooks } = this;
if (key === 'extraReducers') {
return getExtraReducers(hooks[key]);
} else {
return hooks[key];
}
}
}
function getExtraReducers(hook) {
let ret = {};
for (const reducerObj of hook) {
ret = { ...ret, ...reducerObj };
}
return ret;
}
src\redux-logger.tsx
src\redux-logger.tsx
//https://github.com/LogRocket/redux-logger/blob/5816a9fc8da9b417589380e381ed66f1114ebd9a/src/defaults.js#L12-L17
const colors = {
title: 'inherit',
prevState: '#9E9E9E',
action: '#03A9F4',
nextState: '#4CAF50'
}
const logger = ({ dispatch, getState }) => next => (action) => {
let prevState = getState();
let startedTime = Date.now();
let returnedValue = next(action);
let took = Date.now() - startedTime;
let nextState = getState();
const headerCSS: any[] = [];
headerCSS.push('color: gray; font-weight: lighter;');
headerCSS.push(`color: ${colors.title};`);
headerCSS.push('color: gray; font-weight: lighter;');
headerCSS.push('color: gray; font-weight: lighter;');
const title = titleFormatter(action, startedTime, took);
//action %c counter/add %c @ 下午11:17:59 %c (in 2.00 ms) console.log(`%cred%cgreen`, 'color:red', 'color:green');
console.groupCollapsed(`%c ${title}`, ...headerCSS);
console.log('%c prev state', `color: ${colors.prevState}; font-weight: bold`, prevState);
console.log('%c action ', `color: ${colors.action}; font-weight: bold`, action);
console.log('%c next state', `color: ${colors.nextState}; font-weight: bold`, nextState);
console.groupEnd();
return returnedValue;
}
function titleFormatter(action, time, took) {
const parts = ['action'];
parts.push(`%c${String(action.type)}`);
parts.push(`%c@ ${new Date(time).toLocaleTimeString()}`);
parts.push(`%c(in ${took.toFixed(2)} ms)`);
return parts.join(' ');
}
function createLogger() {
return logger;
}
export {
createLogger
}
stateChange
使用
index.tsx
import React from 'react';
import dva, { connect } from './dva';
import { Router, Route, routerRedux, Link } from './dva/router';
import createLoading from './dva-loading';
import dynamic from './dva/dynamic';
import { createLogger } from './redux-logger';
const app = dva({
+ initialState: localStorage.getItem('state') ? JSON.parse(localStorage.getItem('state')!) : {},
+ onStateChange: function () {
+ localStorage.setItem('state', JSON.stringify(arguments[0]));
+ }
});
app.use({ onAction: createLogger() });
app.use(createLoading());
app.model({
namespace: 'counter',
state: { number: 0 },
reducers: {
add(state) {
return { number: state.number + 1 };
}
},
effects: {
*asyncAdd(action, { call, put }) {
yield call(delay, 1000);
yield put({ type: 'counter/add' });
},
*goto({ to }, { put }) {
yield put(routerRedux.push(to));
}
}
});
function Counter(props) {
return (
<div>
<p> {props.loading.models.counter ? 'loading' : props.counter.number}</p>
<button onClick={() => props.dispatch({ type: "counter/add" })}>加1</button>
<button onClick={() => props.dispatch({ type: "counter/asyncAdd" })}>异步+</button>
<button onClick={() => props.dispatch({ type: "counter/goto", to: '/' })}>跳转到/</button>
</div>
)
}
const ConnectedCounter = connect(
(state) => state
)(Counter);
const Home = () => <div>Home</div>;
const UserPageComponent = (dynamic as any)({
app,
models: () => [
import('./models/users'),
],
component: () => import('./routes/UserPage'),
});
app.router((api: any) => (
<Router history={api.history}>
<>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/counter">counter</Link></li>
<li><Link to="/users">users</Link></li>
</ul>
<Route path="/" exact={true} component={Home} />
<Route path="/counter" component={ConnectedCounter} />
<Route path="/users" component={UserPageComponent} />
</>
</Router>
));
app.start('#root');
function delay(ms) {
return new Promise((resolve) => {
setTimeout(function () {
resolve();
}, ms);
});
}
实现
dva\index.tsx
src\dva\index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import * as sagaEffects from 'redux-saga/effects';
import { NAMESPACE_SEP } from './constants';
import { connect, Provider } from 'react-redux';
import { DvaInstance, Router, Model } from './typings';
import prefixNamespace from './prefixNamespace';
import { createHashHistory } from 'history';
import Plugin, { filterHooks } from './plugin';
import { routerMiddleware, connectRouter } from "connected-react-router";
let history = createHashHistory();
export { connect };
export default function (opts: any = {}) {
const app: DvaInstance = {
_models: [],
model,
router,
_router: null,
start
}
const initialReducers = { router: connectRouter(history) };
function model(model: Model) {
const prefixedModel = prefixNamespace(model);
app._models.push(prefixedModel);
return prefixedModel;
}
function router(router: Router) {
app._router = router;
}
const plugin = new Plugin();
plugin.use(filterHooks(opts));
app.use = plugin.use.bind(plugin);
function start(root) {
for (const model of app._models) {
initialReducers[model.namespace] = getReducer(model);
}
let rootReducer = createReducer();
const sagas = getSagas(app);
const sagaMiddleware = createSagaMiddleware();
const extraMiddlewares = plugin.get('onAction');
+ let store = createStore(rootReducer, opts.initialState, applyMiddleware(...extraMiddlewares, routerMiddleware(history), sagaMiddleware));
+ const listeners = plugin.get('onStateChange');
+ for (const listener of listeners) {
+ store.subscribe(() => {
+ listener(store.getState());
+ });
+ }
sagas.forEach(saga => sagaMiddleware.run(saga));
ReactDOM.render(<Provider store={store}>{app._router({ history })}</Provider>, document.querySelector(root))
app.model = injectModel.bind(app);
app._getSaga = getSaga;
function injectModel(m) {
m = model(m);
initialReducers[m.namespace] = getReducer(m);
store.replaceReducer(createReducer());
if (m.effects) {
sagaMiddleware.run(app._getSaga(m.effects, m));
}
if (m.subscriptions) {
runSubscription(m.subscriptions, m, app);
}
}
function runSubscription(subscriptions, model, app) {
for (const key in subscriptions) {
subscriptions[key](
{
dispatch: prefixedDispatch(store.dispatch, model),
history: app._history,
}
);
}
}
function prefixedDispatch(dispatch, model) {
return action => {
const { type } = action;
return dispatch({ ...action, type: prefixType(type, model) });
};
}
function createReducer() {
const extraReducers = plugin.get('extraReducers');
return combineReducers({
...initialReducers,
...extraReducers
});
}
}
function getSagas(app) {
let sagas: Array<any> = [];
for (const model of app._models) {
sagas.push(getSaga(model.effects, model, plugin.get('onEffect')));
}
return sagas;
}
return app;
}
function getSaga(effects, model, onEffect) {
return function* () {
for (const key in effects) {
const watcher = getWatcher(key, model.effects[key], model, onEffect);
yield sagaEffects.fork(watcher);
}
};
}
function getWatcher(key, effect, model, onEffect) {
return function* () {
yield sagaEffects.takeEvery(key, function* sagaWithCatch(...args) {
if (onEffect) {
for (const fn of onEffect) {
effect = fn(effect, sagaEffects, model, key);
}
}
yield effect(...args, { ...sagaEffects, put: action => sagaEffects.put({ ...action, type: prefixType(action.type, model) }) });
});
};
}
function prefixType(type, model) {
if (type.indexOf('/') === -1) {
return `${model.namespace}${NAMESPACE_SEP}${type}`;
}
return type;
}
function getReducer(model) {
let { reducers = {}, state: defaultState } = model;
return (state = defaultState, action) => {
let reducer = reducers[action.type];
if (reducer) {
return reducer(state, action);
}
return state;
}
}
export * from './typings';
src\dva\plugin.tsx
src\dva\plugin.tsx
const hooks = [
'onEffect',
'extraReducers',
'onAction',
+ 'onStateChange'
];
export function filterHooks(obj) {
return Object.keys(obj).reduce((memo, key) => {
if (hooks.indexOf(key) > -1) {
memo[key] = obj[key];
}
return memo;
}, {});
}
export default class Plugin {
hooks: any
constructor() {
this.hooks = hooks.reduce((memo, key) => {
memo[key] = [];
return memo;
}, {});
}
use(plugin) {
const { hooks } = this;
for (const key in plugin) {
hooks[key].push(plugin[key]);
}
}
get(key) {
const { hooks } = this;
if (key === 'extraReducers') {
return getExtraReducers(hooks[key]);
} else {
return hooks[key];
}
}
}
function getExtraReducers(hook) {
let ret = {};
for (const reducerObj of hook) {
ret = { ...ret, ...reducerObj };
}
return ret;
}
onReducer
- redux-undo利用高阶reducer来增强reducer的例子,它主要作用是使任意reducer变成可以执行撤销和重做的全新reducer
使用
index.tsx
import React from 'react';
import dva, { connect } from './dva';
import { Router, Route, routerRedux, Link } from './dva/router';
import createLoading from './dva-loading';
import dynamic from './dva/dynamic';
import { createLogger } from './redux-logger';
+import undoable, { ActionCreators } from './redux-undo';
const app = dva({
initialState: localStorage.getItem('state') ? JSON.parse(localStorage.getItem('state')!) : undefined,
onStateChange: function () {
localStorage.setItem('state', JSON.stringify(arguments[0]));
},
+ onReducer: reducer => {
+ let undoReducer = undoable(reducer);
+ return (state, action) => {
+ let newState: any = undoReducer(state, action);
+ return { ...newState, router: newState.present.router };
+ }
+ }
});
app.use({ onAction: createLogger() });
app.use(createLoading());
app.model({
namespace: 'counter',
state: { number: 0 },
reducers: {
add(state) {
return { number: state.number + 1 };
}
},
effects: {
*asyncAdd(action, { call, put }) {
yield call(delay, 1000);
yield put({ type: 'counter/add' });
},
*goto({ to }, { put }) {
yield put(routerRedux.push(to));
}
}
});
function Counter(props) {
return (
<div>
<p> {props.loading.models.counter ? 'loading' : props.counter.number}</p>
<button onClick={() => props.dispatch({ type: "counter/add" })}>加1</button>
<button onClick={() => props.dispatch({ type: "counter/asyncAdd" })}>异步+</button>
<button onClick={() => props.dispatch({ type: "counter/goto", to: '/' })}>跳转到/</button>
+ <button onClick={() => props.dispatch(ActionCreators.undo())}>undo</button>
+ <button onClick={() => props.dispatch(ActionCreators.redo())}>redo</button>
</div>
)
}
const ConnectedCounter = connect(
+ (state) => state.present
)(Counter);
const Home = () => <div>Home</div>;
const UserPageComponent = (dynamic as any)({
app,
models: () => [
import('./models/users'),
],
component: () => import('./routes/UserPage'),
});
app.router((api: any) => (
<Router history={api.history}>
<>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/counter">counter</Link></li>
<li><Link to="/users">users</Link></li>
</ul>
<Route path="/" exact={true} component={Home} />
<Route path="/counter" component={ConnectedCounter} />
<Route path="/users" component={UserPageComponent} />
</>
</Router>
));
app.start('#root');
function delay(ms) {
return new Promise((resolve) => {
setTimeout(function () {
resolve();
}, ms);
});
}
实现
dva\index.tsx
src\dva\index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import * as sagaEffects from 'redux-saga/effects';
import { NAMESPACE_SEP } from './constants';
import { connect, Provider } from 'react-redux';
import { DvaInstance, Router, Model } from './typings';
import prefixNamespace from './prefixNamespace';
import { createHashHistory } from 'history';
import Plugin, { filterHooks } from './plugin';
import { routerMiddleware, connectRouter } from "connected-react-router";
let history = createHashHistory();
export { connect };
export default function (opts: any = {}) {
const app: DvaInstance = {
_models: [],
model,
router,
_router: null,
start
}
const initialReducers = { router: connectRouter(history) };
function model(model: Model) {
const prefixedModel = prefixNamespace(model);
app._models.push(prefixedModel);
return prefixedModel;
}
function router(router: Router) {
app._router = router;
}
const plugin = new Plugin();
plugin.use(filterHooks(opts));
app.use = plugin.use.bind(plugin);
function start(root) {
for (const model of app._models) {
initialReducers[model.namespace] = getReducer(model);
}
+ const reducerEnhancer = plugin.get('onReducer');
let rootReducer = createReducer();
const sagas = getSagas(app);
const sagaMiddleware = createSagaMiddleware();
const extraMiddlewares = plugin.get('onAction');
let store = createStore(rootReducer, opts.initialState, applyMiddleware(...extraMiddlewares, routerMiddleware(history), sagaMiddleware));
const listeners = plugin.get('onStateChange');
for (const listener of listeners) {
store.subscribe(() => {
listener(store.getState());
});
}
sagas.forEach(saga => sagaMiddleware.run(saga));
ReactDOM.render(<Provider store={store}>{app._router({ history })}</Provider>, document.querySelector(root))
app.model = injectModel.bind(app);
app._getSaga = getSaga;
function injectModel(m) {
m = model(m);
initialReducers[m.namespace] = getReducer(m);
store.replaceReducer(createReducer());
if (m.effects) {
sagaMiddleware.run(app._getSaga(m.effects, m));
}
if (m.subscriptions) {
runSubscription(m.subscriptions, m, app);
}
}
function runSubscription(subscriptions, model, app) {
for (const key in subscriptions) {
subscriptions[key](
{
dispatch: prefixedDispatch(store.dispatch, model),
history: app._history,
}
);
}
}
function prefixedDispatch(dispatch, model) {
return action => {
const { type } = action;
return dispatch({ ...action, type: prefixType(type, model) });
};
}
function createReducer() {
const extraReducers = plugin.get('extraReducers');
+ return reducerEnhancer(combineReducers({
...initialReducers,
...extraReducers
}));
}
}
function getSagas(app) {
let sagas: Array<any> = [];
for (const model of app._models) {
sagas.push(getSaga(model.effects, model, plugin.get('onEffect')));
}
return sagas;
}
return app;
}
function getSaga(effects, model, onEffect) {
return function* () {
for (const key in effects) {
const watcher = getWatcher(key, model.effects[key], model, onEffect);
yield sagaEffects.fork(watcher);
}
};
}
function getWatcher(key, effect, model, onEffect) {
return function* () {
yield sagaEffects.takeEvery(key, function* sagaWithCatch(...args) {
if (onEffect) {
for (const fn of onEffect) {
effect = fn(effect, sagaEffects, model, key);
}
}
yield effect(...args, { ...sagaEffects, put: action => sagaEffects.put({ ...action, type: prefixType(action.type, model) }) });
});
};
}
function prefixType(type, model) {
if (type.indexOf('/') === -1) {
return `${model.namespace}${NAMESPACE_SEP}${type}`;
}
return type;
}
function getReducer(model) {
let { reducers = {}, state: defaultState } = model;
return (state = defaultState, action) => {
let reducer = reducers[action.type];
if (reducer) {
return reducer(state, action);
}
return state;
}
}
export * from './typings';
src\dva\plugin.tsx
src\dva\plugin.tsx
const hooks = [
'onEffect',
'extraReducers',
'onAction',
'onStateChange',
+ 'onReducer'
];
export function filterHooks(obj) {
return Object.keys(obj).reduce((memo, key) => {
if (hooks.indexOf(key) > -1) {
memo[key] = obj[key];
}
return memo;
}, {});
}
export default class Plugin {
hooks: any
constructor() {
this.hooks = hooks.reduce((memo, key) => {
memo[key] = [];
return memo;
}, {});
}
use(plugin) {
const { hooks } = this;
for (const key in plugin) {
hooks[key].push(plugin[key]);
}
}
get(key) {
const { hooks } = this;
if (key === 'extraReducers') {
return getExtraReducers(hooks[key]);
+ } else if (key === 'onReducer') {
+ return getOnReducer(hooks[key]);
+ } else {
return hooks[key];
}
}
}
+function getOnReducer(hook) {
+ return function (reducer) {
+ for (const reducerEnhancer of hook) {
+ reducer = reducerEnhancer(reducer);
+ }
+ return reducer;
+ };
+}
function getExtraReducers(hook) {
let ret = {};
for (const reducerObj of hook) {
ret = { ...ret, ...reducerObj };
}
return ret;
}
src\routes\UserPage.tsx
src\routes\UserPage.tsx
import React from 'react';
import { connect } from "../dva";
function UserPage(props) {
let list = props.list || [];
return (
<>
<button onClick={() => props.dispatch({ type: 'users/asyncAdd' })}>+</button>
<ul>
{
list.map(user => (
<li key={user.id}>{user.name}</li>
))
}
</ul>
</>
)
}
+export default connect(state => state.present.users)(UserPage);
src\redux-undo.tsx
src\redux-undo.tsx
const UNDO_TYPE = "@@redux-unto/UNDO";
const REDO_TYPE = "@@redux-unto/REDO";
export const ActionCreators = {
undo() {
return { type: UNDO_TYPE }
},
redo() {
return { type: REDO_TYPE };
}
}
export default function undoable(reducer) {
let undoType = UNDO_TYPE, redoType = REDO_TYPE;
const initialState = {
past: [],
future: [],
present: reducer(undefined, {})
}
return function (state = initialState, action) {
const { past, present, future } = state;
switch (action.type) {
case undoType:
const previous = past[past.length - 1];
const newPast = past.slice(0, past.length - 1);
return {
past: newPast,
present: previous,
future: [present, ...future]
}
case redoType:
const next = future[0];
const newFuture = future.slice(1);
return {
past: [...past, present],
present: next,
future: newFuture
}
default:
const newPresent = reducer(present, action);
return {
past: [...past, present],
present: newPresent,
future: []
}
}
}
}
extraEnhancers
- redux-persist会将redux的store中的数据缓存到浏览器的localStorage中
使用
index.tsx
import React from 'react';
import dva, { connect } from './dva';
import { Router, Route, routerRedux, Link } from './dva/router';
import createLoading from './dva-loading';
import dynamic from './dva/dynamic';
import { createLogger } from './redux-logger';
import undoable, { ActionCreators } from './redux-undo';
+import { persistStore, persistReducer } from './redux-persist';
+import storage from './redux-persist/lib/storage';
+import { PersistGate } from './redux-persist/lib/integration/react';
+const persistConfig = {
+ key: 'root',
+ storage
+}
const app = dva({
+ //initialState: localStorage.getItem('state') ? JSON.parse(localStorage.getItem('state')!) : undefined,
onStateChange: function () {
+ //localStorage.setItem('state', JSON.stringify(arguments[0]));
+ console.log('currentState', arguments[0]);
},
onReducer: reducer => {
let undoReducer = undoable(reducer);
+ let rootReducer = persistReducer(persistConfig, undoReducer);
return (state, action) => {
+ let newState: any = rootReducer(state, action);
return { ...newState, router: newState.present.router };
}
},
+ extraEnhancers: [
+ createStore => (...args) => {
+ const store: any = createStore(...args);
+ const persistor = persistStore(store);
+ store.persistor = persistor;
+ return store;
+ }
+ ]
});
app.use({ onAction: createLogger() });
app.use(createLoading());
app.model({
namespace: 'counter',
state: { number: 0 },
reducers: {
add(state) {
return { number: state.number + 1 };
}
},
effects: {
*asyncAdd(action, { call, put }) {
yield call(delay, 1000);
yield put({ type: 'counter/add' });
},
*goto({ to }, { put }) {
yield put(routerRedux.push(to));
}
}
});
function Counter(props) {
return (
<div>
<p> {props.loading.models.counter ? 'loading' : props.counter.number}</p>
<button onClick={() => props.dispatch({ type: "counter/add" })}>加1</button>
<button onClick={() => props.dispatch({ type: "counter/asyncAdd" })}>异步加1</button>
<button onClick={() => props.dispatch({ type: "counter/goto", to: '/' })}>跳转到/</button>
<button onClick={() => props.dispatch(ActionCreators.undo())}>undo</button>
<button onClick={() => props.dispatch(ActionCreators.redo())}>redo</button>
</div>
)
}
const ConnectedCounter = connect(
(state) => state.present
)(Counter);
const Home = () => <div>Home</div>;
const UserPageComponent = (dynamic as any)({
app,
models: () => [
import('./models/users'),
],
component: () => import('./routes/UserPage'),
});
app.router((api: any) => (
<PersistGate persistor={(app as any)._store.persistor}>
<Router history={api.history}>
<>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/counter">counter</Link></li>
<li><Link to="/users">users</Link></li>
</ul>
<Route path="/" exact={true} component={Home} />
<Route path="/counter" component={ConnectedCounter} />
<Route path="/users" component={UserPageComponent} />
</>
</Router>
</PersistGate>
));
app.start('#root');
function delay(ms) {
return new Promise((resolve) => {
setTimeout(function () {
resolve();
}, ms);
});
}
实现
dva\index.tsx
src\dva\index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
+import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import createSagaMiddleware from 'redux-saga';
import * as sagaEffects from 'redux-saga/effects';
import { NAMESPACE_SEP } from './constants';
import { connect, Provider } from 'react-redux';
import { DvaInstance, Router, Model } from './typings';
import prefixNamespace from './prefixNamespace';
import { createHashHistory } from 'history';
import Plugin, { filterHooks } from './plugin';
import { routerMiddleware, connectRouter } from "connected-react-router";
let history = createHashHistory();
export { connect };
export default function (opts: any = {}) {
const app: DvaInstance = {
_models: [],
model,
router,
_router: null,
start
}
const initialReducers = { router: connectRouter(history) };
function model(model: Model) {
const prefixedModel = prefixNamespace(model);
app._models.push(prefixedModel);
return prefixedModel;
}
function router(router: Router) {
app._router = router;
}
const plugin = new Plugin();
plugin.use(filterHooks(opts));
app.use = plugin.use.bind(plugin);
function start(root) {
for (const model of app._models) {
initialReducers[model.namespace] = getReducer(model);
}
const reducerEnhancer = plugin.get('onReducer');
let rootReducer = createReducer();
const sagas = getSagas(app);
const sagaMiddleware = createSagaMiddleware();
const extraMiddlewares = plugin.get('onAction');
+ const extraEnhancers = plugin.get('extraEnhancers');
+ const enhancers = [...extraEnhancers, applyMiddleware(...extraMiddlewares, routerMiddleware(history), sagaMiddleware)];
+ //let store = createStore(rootReducer, opts.initialState, applyMiddleware(...extraMiddlewares, routerMiddleware(history), sagaMiddleware));
+ let store = createStore(rootReducer, opts.initialState, compose(...enhancers));
+ app._store = store;
const listeners = plugin.get('onStateChange');
for (const listener of listeners) {
store.subscribe(() => {
listener(store.getState());
});
}
sagas.forEach(saga => sagaMiddleware.run(saga));
ReactDOM.render(<Provider store={store}>{app._router({ history })}</Provider>, document.querySelector(root))
app.model = injectModel.bind(app);
app._getSaga = getSaga;
function injectModel(m) {
m = model(m);
initialReducers[m.namespace] = getReducer(m);
store.replaceReducer(createReducer());
if (m.effects) {
sagaMiddleware.run(app._getSaga(m.effects, m));
}
if (m.subscriptions) {
runSubscription(m.subscriptions, m, app);
}
}
function runSubscription(subscriptions, model, app) {
for (const key in subscriptions) {
subscriptions[key](
{
dispatch: prefixedDispatch(store.dispatch, model),
history: app._history,
}
);
}
}
function prefixedDispatch(dispatch, model) {
return action => {
const { type } = action;
return dispatch({ ...action, type: prefixType(type, model) });
};
}
function createReducer() {
const extraReducers = plugin.get('extraReducers');
return reducerEnhancer(combineReducers({
...initialReducers,
...extraReducers
}));
}
}
function getSagas(app) {
let sagas: Array<any> = [];
for (const model of app._models) {
sagas.push(getSaga(model.effects, model, plugin.get('onEffect')));
}
return sagas;
}
return app;
}
function getSaga(effects, model, onEffect) {
return function* () {
for (const key in effects) {
const watcher = getWatcher(key, model.effects[key], model, onEffect);
yield sagaEffects.fork(watcher);
}
};
}
function getWatcher(key, effect, model, onEffect) {
return function* () {
yield sagaEffects.takeEvery(key, function* sagaWithCatch(...args) {
if (onEffect) {
for (const fn of onEffect) {
effect = fn(effect, sagaEffects, model, key);
}
}
yield effect(...args, { ...sagaEffects, put: action => sagaEffects.put({ ...action, type: prefixType(action.type, model) }) });
});
};
}
function prefixType(type, model) {
if (type.indexOf('/') === -1) {
return `${model.namespace}${NAMESPACE_SEP}${type}`;
}
return type;
}
function getReducer(model) {
let { reducers = {}, state: defaultState } = model;
return (state = defaultState, action) => {
let reducer = reducers[action.type];
if (reducer) {
return reducer(state, action);
}
return state;
}
}
export * from './typings';
plugin.tsx
src\dva\plugin.tsx
const hooks = [
'onEffect',
'extraReducers',
'onAction',
'onStateChange',
'onReducer',
+ "extraEnhancers"
];
export function filterHooks(obj) {
return Object.keys(obj).reduce((memo, key) => {
if (hooks.indexOf(key) > -1) {
memo[key] = obj[key];
}
return memo;
}, {});
}
export default class Plugin {
hooks: any
constructor() {
this.hooks = hooks.reduce((memo, key) => {
memo[key] = [];
return memo;
}, {});
}
use(plugin) {
const { hooks } = this;
for (const key in plugin) {
+ if (key === 'extraEnhancers') {
+ hooks[key] = plugin[key];
+ } else {
+ hooks[key].push(plugin[key]);
+ }
}
}
get(key) {
const { hooks } = this;
if (key === 'extraReducers') {
return getExtraReducers(hooks[key]);
} else if (key === 'onReducer') {
return getOnReducer(hooks[key]);
} else {
return hooks[key];
}
}
}
function getOnReducer(hook) {
return function (reducer) {
for (const reducerEnhancer of hook) {
reducer = reducerEnhancer(reducer);
}
return reducer;
};
}
function getExtraReducers(hook) {
let ret = {};
for (const reducerObj of hook) {
ret = { ...ret, ...reducerObj };
}
return ret;
}
redux-persist\index.tsx
src\redux-persist\index.tsx
import persistReducer from './persistReducer';
import persistStore from './persistStore';
export {
persistReducer,
persistStore
}
export const REHYDRATE = 'REHYDRATE';
persistReducer.tsx
src\redux-persist\persistReducer.tsx
export default function (persistConfig, reducer) {
let isInited = false;
return (state, action) => {
switch (action.type) {
case 'PERSIST_INIT':
isInited = true;
let value = persistConfig.storage.getItem('persist:' + persistConfig.key);
state = value ? JSON.parse(value) : undefined;
return reducer(state, action);
default:
if (isInited) {
state = reducer(state, action);
persistConfig.storage.setItem('persist:' + persistConfig.key, JSON.stringify(state));
return state;
}
return reducer(state, action);
}
}
}
persistStore.tsx
src\redux-persist\persistStore.tsx
export default function (store) {
let persistor = {
...store,
initState() {
persistor.dispatch({
type: 'PERSIST_INIT',
})
}
};
return persistor;
}
redux-persist\lib\storage.tsx
src\redux-persist\lib\storage.tsx
let storage = {
setItem(key, val) {
localStorage.setItem(key, val);
},
getItem(key) {
return localStorage.getItem(key);
}
}
export default storage;
redux-persist\lib\integration\react.tsx
src\redux-persist\lib\integration\react.tsx
import React, { Component } from 'react';
class PersistGate extends Component<any> {
componentDidMount() {
this.props.persistor.initState();
}
render() {
return this.props.children;
}
}
export { PersistGate }
dva-immer
- immer是
mobx
的作者写的一个immutable
库,核心实现是利用 ES6 的 proxy,几乎以最小的成本实现了 js 的不可变数据结构 - dva-immer
currentState
被操作对象的最初状态draftState
根据 currentState 生成的草稿状态,它是 currentState 的代理,对 draftState 所做的任何修改都将被记录并用于生成 nextState 。在此过程中,currentState 将不受影响nextState
根据 draftState 生成的最终状态produce
生产 用来生成 nextState的函数
cnpm i dva-immer -S
import produce from "immer"
const baseState = [
{
todo: "Learn typescript",
done: true
},
{
todo: "Try immer",
done: false
}
]
const nextState = produce(baseState, draftState => {
draftState.push({todo: "Tweet about it"})
draftState[1].done = true
})
使用
index.tsx
import React from 'react';
import dva, { connect } from './dva';
import { Router, Route, routerRedux, Link } from './dva/router';
import createLoading from './dva-loading';
import dynamic from './dva/dynamic';
import { createLogger } from './redux-logger';
import undoable, { ActionCreators } from './redux-undo';
import { persistStore, persistReducer } from './redux-persist';
import storage from './redux-persist/lib/storage';
import { PersistGate } from './redux-persist/lib/integration/react';
+import immer from './dva-immer';
const persistConfig = {
key: 'root',
storage
}
const app = dva({
//initialState: localStorage.getItem('state') ? JSON.parse(localStorage.getItem('state')!) : undefined,
onStateChange: function () {
//localStorage.setItem('state', JSON.stringify(arguments[0]));
console.log('currentState', arguments[0]);
},
onReducer: reducer => {
let undoReducer = undoable(reducer);
let rootReducer = persistReducer(persistConfig, undoReducer);
return (state, action) => {
let newState: any = rootReducer(state, action);
+ return { ...newState, router: newState.present ? newState.present.router : null };
}
},
extraEnhancers: [
createStore => (...args) => {
const store: any = createStore(...args);
const persistor = persistStore(store);
store.persistor = persistor;
return store;
}
]
});
app.use({ onAction: createLogger() });
app.use(createLoading());
+app.use(immer());
app.model({
namespace: 'counter',
state: { number: 0 },
reducers: {
add(state) {
return { number: state.number + 1 };
}
},
effects: {
*asyncAdd(action, { call, put }) {
yield call(delay, 1000);
yield put({ type: 'counter/add' });
},
*goto({ to }, { put }) {
yield put(routerRedux.push(to));
}
}
});
function Counter(props) {
return (
<div>
<p> {props.loading.models.counter ? 'loading' : props.counter.number}</p>
<button onClick={() => props.dispatch({ type: "counter/add" })}>加1</button>
<button onClick={() => props.dispatch({ type: "counter/asyncAdd" })}>异步加1</button>
<button onClick={() => props.dispatch({ type: "counter/goto", to: '/' })}>跳转到/</button>
<button onClick={() => props.dispatch(ActionCreators.undo())}>undo</button>
<button onClick={() => props.dispatch(ActionCreators.redo())}>redo</button>
</div>
)
}
const ConnectedCounter = connect(
(state) => state.present
)(Counter);
const Home = () => <div>Home</div>;
const UserPageComponent = (dynamic as any)({
app,
models: () => [
import('./models/users'),
],
component: () => import('./routes/UserPage'),
});
app.router((api: any) => (
<PersistGate persistor={(app as any)._store.persistor}>
<Router history={api.history}>
<>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/counter">counter</Link></li>
<li><Link to="/users">users</Link></li>
</ul>
<Route path="/" exact={true} component={Home} />
<Route path="/counter" component={ConnectedCounter} />
<Route path="/users" component={UserPageComponent} />
</>
</Router>
</PersistGate>
));
app.start('#root');
function delay(ms) {
return new Promise((resolve) => {
setTimeout(function () {
resolve();
}, ms);
});
}
实现
dva\index.tsx
src\dva\index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import createSagaMiddleware from 'redux-saga';
import * as sagaEffects from 'redux-saga/effects';
import { NAMESPACE_SEP } from './constants';
import { connect, Provider } from 'react-redux';
import { DvaInstance, Router, Model } from './typings';
import prefixNamespace from './prefixNamespace';
import { createHashHistory } from 'history';
import Plugin, { filterHooks } from './plugin';
import { routerMiddleware, connectRouter } from "connected-react-router";
let history = createHashHistory();
export { connect };
export default function (opts: any = {}) {
const app: DvaInstance = {
_models: [],
model,
router,
_router: null,
start
}
const initialReducers = { router: connectRouter(history) };
function model(model: Model) {
const prefixedModel = prefixNamespace(model);
app._models.push(prefixedModel);
return prefixedModel;
}
function router(router: Router) {
app._router = router;
}
const plugin = new Plugin();
plugin.use(filterHooks(opts));
app.use = plugin.use.bind(plugin);
function start(root) {
for (const model of app._models) {
+ initialReducers[model.namespace] = getReducer(model, plugin._handleActions);
}
const reducerEnhancer = plugin.get('onReducer');
let rootReducer = createReducer();
const sagas = getSagas(app);
const sagaMiddleware = createSagaMiddleware();
const extraMiddlewares = plugin.get('onAction');
const extraEnhancers = plugin.get('extraEnhancers');
const enhancers = [...extraEnhancers, applyMiddleware(...extraMiddlewares, routerMiddleware(history), sagaMiddleware)];
//let store = createStore(rootReducer, opts.initialState, applyMiddleware(...extraMiddlewares, routerMiddleware(history), sagaMiddleware));
let store = createStore(rootReducer, opts.initialState, compose(...enhancers));
app._store = store;
const listeners = plugin.get('onStateChange');
for (const listener of listeners) {
store.subscribe(() => {
listener(store.getState());
});
}
sagas.forEach(saga => sagaMiddleware.run(saga));
ReactDOM.render(<Provider store={store}>{app._router({ history })}</Provider>, document.querySelector(root))
app.model = injectModel.bind(app);
app._getSaga = getSaga;
function injectModel(m) {
m = model(m);
+ initialReducers[m.namespace] = getReducer(m, plugin._handleActions);
store.replaceReducer(createReducer());
if (m.effects) {
sagaMiddleware.run(app._getSaga(m.effects, m));
}
if (m.subscriptions) {
runSubscription(m.subscriptions, m, app);
}
}
function runSubscription(subscriptions, model, app) {
for (const key in subscriptions) {
subscriptions[key](
{
dispatch: prefixedDispatch(store.dispatch, model),
history: app._history,
}
);
}
}
function prefixedDispatch(dispatch, model) {
return action => {
const { type } = action;
return dispatch({ ...action, type: prefixType(type, model) });
};
}
function createReducer() {
const extraReducers = plugin.get('extraReducers');
return reducerEnhancer(combineReducers({
...initialReducers,
...extraReducers
}));
}
}
function getSagas(app) {
let sagas: Array<any> = [];
for (const model of app._models) {
sagas.push(getSaga(model.effects, model, plugin.get('onEffect')));
}
return sagas;
}
return app;
}
function getSaga(effects, model, onEffect) {
return function* () {
for (const key in effects) {
const watcher = getWatcher(key, model.effects[key], model, onEffect);
yield sagaEffects.fork(watcher);
}
};
}
function getWatcher(key, effect, model, onEffect) {
return function* () {
yield sagaEffects.takeEvery(key, function* sagaWithCatch(...args) {
if (onEffect) {
for (const fn of onEffect) {
effect = fn(effect, sagaEffects, model, key);
}
}
yield effect(...args, { ...sagaEffects, put: action => sagaEffects.put({ ...action, type: prefixType(action.type, model) }) });
});
};
}
function prefixType(type, model) {
if (type.indexOf('/') === -1) {
return `${model.namespace}${NAMESPACE_SEP}${type}`;
}
return type;
}
function getReducer(model, handleActions) {
let { reducers = {}, state: defaultState } = model;
+ let reducer = (state = defaultState, action) => {
let reducer = reducers[action.type];
if (reducer) {
return reducer(state, action);
}
return state;
}
+ if (handleActions) {
+ return handleActions(reducers || {}, defaultState);
+ }
+ return reducer;
}
export * from './typings';
dva\plugin.tsx
src\dva\plugin.tsx
const hooks = [
'onEffect',
'extraReducers',
'onAction',
'onStateChange',
'onReducer',
"extraEnhancers",
+ '_handleActions'
];
export function filterHooks(obj) {
return Object.keys(obj).reduce((memo, key) => {
if (hooks.indexOf(key) > -1) {
memo[key] = obj[key];
}
return memo;
}, {});
}
export default class Plugin {
hooks: any
+ _handleActions: any = null
constructor() {
this.hooks = hooks.reduce((memo, key) => {
memo[key] = [];
return memo;
}, {});
}
use(plugin) {
const { hooks } = this;
for (const key in plugin) {
+ if (key === '_handleActions') {
+ this._handleActions = plugin[key];
} else if (key === 'extraEnhancers') {
hooks[key] = plugin[key];
} else {
hooks[key].push(plugin[key]);
}
}
}
get(key) {
const { hooks } = this;
if (key === 'extraReducers') {
return getExtraReducers(hooks[key]);
} else if (key === 'onReducer') {
return getOnReducer(hooks[key]);
} else {
return hooks[key];
}
}
}
function getOnReducer(hook) {
return function (reducer) {
for (const reducerEnhancer of hook) {
reducer = reducerEnhancer(reducer);
}
return reducer;
};
}
function getExtraReducers(hook) {
let ret = {};
for (const reducerObj of hook) {
ret = { ...ret, ...reducerObj };
}
return ret;
}
dva-immer.tsx
src\dva-immer.tsx
import produce from 'immer';
export default function () {
return {
_handleActions(handlers, defaultState) {
return (state = defaultState, action) => {
const { type } = action;
const ret = produce(state, draft => {
const handler = handlers[type];
if (handler) {
return handler(draft, action);
}
});
return ret || {};
};
},
};
}
onError
使用
index.tsx
import React from 'react';
import dva, { connect } from './dva';
import { Router, Route, routerRedux, Link } from './dva/router';
import createLoading from './dva-loading';
import dynamic from './dva/dynamic';
import { createLogger } from './redux-logger';
import undoable, { ActionCreators } from './redux-undo';
import { persistStore, persistReducer } from './redux-persist';
import storage from './redux-persist/lib/storage';
import { PersistGate } from './redux-persist/lib/integration/react';
import immer from './dva-immer';
const persistConfig = {
key: 'root',
storage
}
const app = dva({
//initialState: localStorage.getItem('state') ? JSON.parse(localStorage.getItem('state')!) : undefined,
onStateChange: function () {
//localStorage.setItem('state', JSON.stringify(arguments[0]));
console.log('currentState', arguments[0]);
},
onReducer: reducer => {
let undoReducer = undoable(reducer);
let rootReducer = persistReducer(persistConfig, undoReducer);
return (state, action) => {
let newState: any = rootReducer(state, action);
return { ...newState, router: newState.present ? newState.present.router : null };
}
},
extraEnhancers: [
createStore => (...args) => {
const store: any = createStore(...args);
const persistor = persistStore(store);
store.persistor = persistor;
return store;
}
],
+ onError(err, dispatch) {
+ console.error('onError', err);
+ }
});
app.use({ onAction: createLogger() });
app.use(createLoading());
app.use(immer());
app.model({
namespace: 'counter',
state: { number: 0 },
reducers: {
add(state) {
return { number: state.number + 1 };
}
},
effects: {
*asyncAdd(action, { call, put }) {
yield call(delay, 1000);
yield put({ type: 'counter/add' });
+ throw new Error('asyncAdd');
},
*goto({ to }, { put }) {
yield put(routerRedux.push(to));
}
},
+ subscriptions: {
+ changeTitle({ dispatch, history }, done) {
+ console.log('changeTitle');
+ done('出错啦');
+ }
+ }
});
function Counter(props) {
return (
<div>
<p> {props.loading.models.counter ? 'loading' : props.counter.number}</p>
<button onClick={() => props.dispatch({ type: "counter/add" })}>加1</button>
<button onClick={() => props.dispatch({ type: "counter/asyncAdd" })}>异步加1</button>
<button onClick={() => props.dispatch({ type: "counter/goto", to: '/' })}>跳转到/</button>
<button onClick={() => props.dispatch(ActionCreators.undo())}>undo</button>
<button onClick={() => props.dispatch(ActionCreators.redo())}>redo</button>
</div>
)
}
const ConnectedCounter = connect(
(state) => state.present
)(Counter);
const Home = () => <div>Home</div>;
const UserPageComponent = (dynamic as any)({
app,
models: () => [
import('./models/users'),
],
component: () => import('./routes/UserPage'),
});
app.router((api: any) => (
<PersistGate persistor={(app as any)._store.persistor}>
<Router history={api.history}>
<>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/counter">counter</Link></li>
<li><Link to="/users">users</Link></li>
</ul>
<Route path="/" exact={true} component={Home} />
<Route path="/counter" component={ConnectedCounter} />
<Route path="/users" component={UserPageComponent} />
</>
</Router>
</PersistGate>
));
app.start('#root');
function delay(ms) {
return new Promise((resolve) => {
setTimeout(function () {
resolve();
}, ms);
});
}
实现
src\dva\index.tsx
src\dva\index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import createSagaMiddleware from 'redux-saga';
import * as sagaEffects from 'redux-saga/effects';
import { NAMESPACE_SEP } from './constants';
import { connect, Provider } from 'react-redux';
import { DvaInstance, Router, Model } from './typings';
import prefixNamespace from './prefixNamespace';
import { createHashHistory } from 'history';
import Plugin, { filterHooks } from './plugin';
import { routerMiddleware, connectRouter } from "connected-react-router";
let history = createHashHistory();
export { connect };
export default function (opts: any = {}) {
const app: DvaInstance = {
_models: [],
model,
router,
_router: null,
start
}
const initialReducers = { router: connectRouter(history) };
function model(model: Model) {
const prefixedModel = prefixNamespace(model);
app._models.push(prefixedModel);
return prefixedModel;
}
function router(router: Router) {
app._router = router;
}
const plugin = new Plugin();
plugin.use(filterHooks(opts));
app.use = plugin.use.bind(plugin);
function start(root) {
for (const model of app._models) {
initialReducers[model.namespace] = getReducer(model, plugin._handleActions);
}
const reducerEnhancer = plugin.get('onReducer');
let rootReducer = createReducer();
const sagas = getSagas(app);
const sagaMiddleware = createSagaMiddleware();
const extraMiddlewares = plugin.get('onAction');
const extraEnhancers = plugin.get('extraEnhancers');
const enhancers = [...extraEnhancers, applyMiddleware(...extraMiddlewares, routerMiddleware(history), sagaMiddleware)];
//let store = createStore(rootReducer, opts.initialState, applyMiddleware(...extraMiddlewares, routerMiddleware(history), sagaMiddleware));
let store = createStore(rootReducer, opts.initialState, compose(...enhancers));
app._store = store;
const listeners = plugin.get('onStateChange');
for (const listener of listeners) {
store.subscribe(() => {
listener(store.getState());
});
}
sagas.forEach(saga => sagaMiddleware.run(saga));
ReactDOM.render(<Provider store={store}>{app._router({ history })}</Provider>, document.querySelector(root))
app.model = injectModel.bind(app);
app._getSaga = getSaga;
+ for (const model of app._models) {
+ if (model.subscriptions) {
+ runSubscription(model.subscriptions, model, app, plugin.get('onError'));
+ }
+ }
function injectModel(m) {
m = model(m);
initialReducers[m.namespace] = getReducer(m, plugin._handleActions);
store.replaceReducer(createReducer());
if (m.effects) {
sagaMiddleware.run(app._getSaga(m.effects, m));
}
if (m.subscriptions) {
runSubscription(m.subscriptions, m, app, plugin.get('onError'));
}
}
+ function runSubscription(subscriptions, model, app, onError) {
for (const key in subscriptions) {
+ let dispatch = prefixedDispatch(store.dispatch, model);
subscriptions[key](
{
+ dispatch,
history: app._history,
+ }, err => {
+ for (let fn of onError) {
+ fn(err, dispatch);
+ }
+ }
);
}
}
function prefixedDispatch(dispatch, model) {
return action => {
const { type } = action;
return dispatch({ ...action, type: prefixType(type, model) });
};
}
function createReducer() {
const extraReducers = plugin.get('extraReducers');
return reducerEnhancer(combineReducers({
...initialReducers,
...extraReducers
}));
}
}
function getSagas(app) {
let sagas: Array<any> = [];
for (const model of app._models) {
+ sagas.push(getSaga(model.effects, model, plugin.get('onEffect'), plugin.get('onError')));
}
return sagas;
}
return app;
}
+function getSaga(effects, model, onEffect, onError) {
return function* () {
for (const key in effects) {
+ const watcher = getWatcher(key, model.effects[key], model, onEffect, onError);
yield sagaEffects.fork(watcher);
}
};
}
+function getWatcher(key, effect, model, onEffect, onError) {
return function* () {
yield sagaEffects.takeEvery(key, function* sagaWithCatch(...args) {
if (onEffect) {
for (const fn of onEffect) {
effect = fn(effect, sagaEffects, model, key);
}
}
+ try {
yield effect(...args, { ...sagaEffects, put: action => sagaEffects.put({ ...action, type: prefixType(action.type, model) }) });
+ } catch (err) {
+ for (const fn of onError) {
+ fn(err);
+ }
+ }
});
};
}
function prefixType(type, model) {
if (type.indexOf('/') === -1) {
return `${model.namespace}${NAMESPACE_SEP}${type}`;
}
return type;
}
function getReducer(model, handleActions) {
let { reducers = {}, state: defaultState } = model;
let reducer = (state = defaultState, action) => {
let reducer = reducers[action.type];
if (reducer) {
return reducer(state, action);
}
return state;
}
if (handleActions) {
return handleActions(reducers || {}, defaultState);
}
return reducer;
}
export * from './typings';
src\dva\plugin.tsx
src\dva\plugin.tsx
const hooks = [
'onEffect',
'extraReducers',
'onAction',
'onStateChange',
'onReducer',
"extraEnhancers",
'_handleActions',
+ "onError"
];
export function filterHooks(obj) {
return Object.keys(obj).reduce((memo, key) => {
if (hooks.indexOf(key) > -1) {
memo[key] = obj[key];
}
return memo;
}, {});
}
export default class Plugin {
hooks: any
_handleActions: any = null
constructor() {
this.hooks = hooks.reduce((memo, key) => {
memo[key] = [];
return memo;
}, {});
}
use(plugin) {
const { hooks } = this;
for (const key in plugin) {
if (key === '_handleActions') {
this._handleActions = plugin[key];
} else if (key === 'extraEnhancers') {
hooks[key] = plugin[key];
} else {
hooks[key].push(plugin[key]);
}
}
}
get(key) {
const { hooks } = this;
if (key === 'extraReducers') {
return getExtraReducers(hooks[key]);
} else if (key === 'onReducer') {
return getOnReducer(hooks[key]);
} else {
return hooks[key];
}
}
}
function getOnReducer(hook) {
return function (reducer) {
for (const reducerEnhancer of hook) {
reducer = reducerEnhancer(reducer);
}
return reducer;
};
}
function getExtraReducers(hook) {
let ret = {};
for (const reducerObj of hook) {
ret = { ...ret, ...reducerObj };
}
return ret;
}