react dva 碎片02

8 篇文章 0 订阅
2 篇文章 0 订阅

dva 是基于现有应用架构 (redux + react-router + redux-saga 等)的一层轻量封装,没有引入任何新概念,全部代码不到 100 行。( Inspired by elm and choo. )

dva 是 framework,不是 library,类似 emberjs,会很明确地告诉你每个部件应该怎么写,这对于团队而言,会更可控。另外,除了 react 和 react-dom 是 peerDependencies 以外,dva 封装了所有其他依赖。

DVA一共有5个API

import dva, { connect } from 'dva';

// 1. Create app
const app = dva();

// 2. Add plugins (optionally)
app.use(plugin);

// 3. Register models
app.model(model);

// 4. Connect components and models
const App = connect(mapStateToProps)(Component);

// 5. Config router with Components
app.router(routes);

// 6. Start app
app.start('#root');

API

1. app = dva(opts)

新建一个dva app,你可以配置history和initialState选项。

  • opts.history: the history for router, default: hashHistory

  • opts.initialState: initialState of the app, default: {}

import { browserHistory } from 'dva/router';
const app = dva({ 
  history: browserHistory,
});

2. app.use(hooks)

  • onError(fn): called when an effect or subscription emit an error
  • onAction(array|fn): called when an action is dispatched, used for registering redux middleware, support Arrayfor convenience
  • onStateChange(fn): called after a reducer changes the state
  • onReducer(fn): used for apply reducer enhancer
  • onEffect(fn): used for wrapping effect to add custom behavior, e.g. dva-loading for automatical loading state
  • onHmr(fn): used for hot module replacement
  • extraReducers(object): used for adding extra reducers, e.g. redux-form needs extra form reducer

3. app.model(obj)

  • namespace:model的名称空间
  • state:初始state
  • reducers:同步的修改状态的操作,由actions触发(state, action) => state
  • effects:异步的操作,并不直接修改state,由actions触发,也可以调用actions。(action, { put, call, select })
  • subscriptions:异步的只读操作,并不直接修改state,可以调用actions。({ dispatch, history })

put(action)dispatch(action)
这里effects中的put(action)等同于subscriptions中的dispatch(action),它们的作用都是分发一个action。

yield put({ type: actionType, payload: attachedData, error: errorIfHave});
dispatch({ type: actionType, payload: attachedData, error: errorIfHave});

call(asyncFunction)
调用一个异步函数

const result = yield call(api.fetch, { page: 1 });

select(function)
从全局状态中选择数据

const count = yield select(state => state.count);

4. app.router(({ history }) => routes)

import { Router, Route } from 'dva/routes';
app.router(({ history } => ({
  <Router history={ history }>
    <Route path="/" component={App} />
  </Router>
});

5. app.start(selector?)

启动应用,selector是可选的。如果没有selector参数,它会返回一个函数,这个函数返回JSX元素。

https://github.com/dvajs/dva

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值