想一下,若是你须要写一个基于Redux 的项目,你须要重复的写很是多的Action Constants,很是多的Action Creator以作至关大一部分差很少相同的事情。前端
因而出现了为了帮你减小书写重复Constants及Action Creator 的库redux-act。react
但只有Redux并不能彻底知足咱们的业务需求,毕竟SPA项目中老是须要从服务端获取数据的,因而这时候咱们整合进来Redux-saga。git
Redux-saga能很是好的帮助咱们处理异步事件,可是一样的,Redux-saga须要书写许多的Action Creator并指定其Take类型再合并到Redux-Saga的入口处,并且这些Action Creator及effect非但须要一一让参数对应,还不方便作统一的事件处理。github
因而Saga-action-creator诞生了。typescript
使用Saga-action-creator的方法很是简单,只需3步redux
import createSagaActions from 'saga-action-creator';
import { takeLatest, call } from 'redux-saga/effects';
import { getUserInfo, updateUser } from '../services/user';
const user = createSagaActions({
// 通常状况下,你能够直接写一个Effect
*getUserById(id: string): Generator<any, any, any> {
yield call(getUserInfo, id);
},
// 固然,若是你须要为某一个Effect指定take的类型
// 你能够传递一个对象,并指定takeType属性
updateUser: {
takeType: takeLatest,
*effect(id: string, name: string): Generator<any, any, any> {
yield call(updateUser, id, { name });
},
},
});
export default user;
复制代码
import { createConnection, getLoadingPlugin } from 'saga-action-creator';
import user from './user';
import { takeLatest } from 'redux-saga/effects';
const creator = createConnection({
// 合并creator
creators: {
user,
},
// 默认状况下effect的take类型为 `takeEvery`
// 若是你须要修改默认的类型能够传递这个参数
defaultTakeType: takeLatest,
// 添加插件
plugins: {
// 这里插件的key将做为后面getReducers的导出的key,则为store名
loading: getLoadingPlugin(),
},
});
export default creator;
复制代码
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { all } from 'redux-saga/effects';
import createSagaMiddleware from 'redux-saga';
import creator from '../sagas';
// 将插件导出的reducers与store链接
const reducers = combineReducers({
...creator.getReducers(),
});
const sagaMiddleware = createSagaMiddleware();
// 将Effects与Redux-saga链接
sagaMiddleware.run(function*() {
yield all(creator.getEffects());
});
const store = createStore(reducers, applyMiddleware(sagaMiddleware));
export type AppState = ReturnType<typeof reducers>;
export default store;
复制代码
至此,saga-action-creator的链接动做就所有作完了。app
剩下的,你就只须要像平时使用action同样使用creator为你导出的Action Creator了。框架
import { connect } from 'react-redux';
import { AppState } from '../store';
import userActions from '../sagaActions/user';
import UserList from './UserList';
const mapStateToProps = (state: AppState) => ({
loading: state.loading.user.getUserById,
});
const mapDispatchToProps = {
getUserById: userActions.actions.getUserById,
};
export default connect(
mapStateToProps,
mapDispatchToProps,
)(UserList);
复制代码
整个库很是的精简,旨在为你解决核心痛点。简化Redux-saga的书写,并保留其全部优势。异步
与历史项目整合也很是简单,不须要作过多的修改,使你能够渐进地优化你的项目。测试
该库使用严谨的Ts类型开发,并进行自动类型推导,使你能够彻底体会到Ts带来的开发乐趣。
该库支持插件,能够在全部的Effect先后执行所需的操做(这里开发的loading插件灵感源自rematch,十分感谢)。
该库开源并遵循MIT开源协议
咱们在招人😎
AfterShip 2012 年成立于香港,公司自2014年起已实现持续盈利,且每一年 100% 增加,公司目前暂时不须要融资。业务遍及全球,与全球 500 多家物流公司达成合做,涉及 30 多种主流语言业务体系。客户有 Amazon, Wish, eBay, Paypal, Groupon, Etsy,及各大小电商超过 100,000 家。
咱们位于深圳南山互联网最繁华的地带。
咱们前端全面使用React.js做为核心框架。若是你有一年以上的前端开发工做,熟悉React.js,热爱各类最新技术,对代码有要求,欢迎给我你的简历:qc.zhu@aftership.com