Redux-GeneratorRedux 的中间件
Redux 中间件, 允许你发起一个ES6 generator 函数类型的action。
可以借由generator的特性,在业务中处理一些流程控制(状态流转),批量处理之类的场景。
用法示例
首先,应用中间件
import {applyMiddleware, createStore} from 'redux'; // import redux-generator import {generator} from 'redux-generator'; // or // import generator from 'redux-generator/lib/generator' // reducers in your project. import reducers from './path/to/your/reducers'; // apply redux-generator const createStoreWithMiddleware = applyMiddleware(generator)(createStore); const store = createStoreWithMiddleware(reducers);
编写 action 创造器
// in ./actions/userActionsCreator.js export const doSaveUser = (user) => { return function *(dispatch, getState) { // async dispatch an action dispatch({type: 'LOADING', payload: 'Loading...'}); // sync waterfall: a plain object yield let params = yield Object.assign({}, user, {lastModified: new Date().getTime()}); // async dispatch an action dispatch({type: 'WILL_SAVE_USER', payload: params}); // sync waterfall: a promise yield let payload = yield new Promise(resolve=> { process.nextTick(()=> { params.id = '1'; resolve(params); }); }); // async dispatch an action dispatch({type: 'DID_SAVE_USER', payload}); // sync waterfall: a thunk yield let redirect = yield ()=> { if (payload && payload.id) { return {type: 'ROUTING_POP', payload: `/user/${payload.id}`}; } }; // Only this ending action will be dispatched by generator middleware after all return redirect; }; }
评论