DVA簡介
dva 是基于現(xiàn)有應(yīng)用架構(gòu) (redux + react-router + redux-saga 等)的一層輕量封裝,沒有引入任何新概念帖努,全部代碼不到 100 行乐疆。( Inspired by elm and choo. )
dva 是 framework,不是 library,類似 emberjs脑奠,會(huì)很明確地告訴你每個(gè)部件應(yīng)該怎么寫,這對于團(tuán)隊(duì)而言幅慌,會(huì)更可控宋欺。另外,除了 react 和 react-dom 是 peerDependencies 以外胰伍,dva 封裝了所有其他依賴齿诞。
DVA一共有5個(gè)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)
新建一個(gè)dva app,你可以配置history和initialState選項(xiàng)骂租。
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:同步的修改狀態(tài)的操作祷杈,由actions觸發(fā)
(state, action) => state
-
effects:異步的操作,并不直接修改state渗饮,由actions觸發(fā)但汞,也可以調(diào)用actions。
(action, { put, call, select })
-
subscriptions:異步的只讀操作互站,并不直接修改state私蕾,可以調(diào)用actions。
({ dispatch, history })
put(action)和dispatch(action)
這里effects中的put(action)等同于subscriptions中的dispatch(action)胡桃,它們的作用都是分發(fā)一個(gè)action踩叭。
yield put({ type: actionType, payload: attachedData, error: errorIfHave});
dispatch({ type: actionType, payload: attachedData, error: errorIfHave});
call(asyncFunction)
調(diào)用一個(gè)異步函數(shù)
const result = yield call(api.fetch, { page: 1 });
select(function)
從全局狀態(tài)中選擇數(shù)據(jù)
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?)
啟動(dòng)應(yīng)用,selector是可選的翠胰。如果沒有selector參數(shù)容贝,它會(huì)返回一個(gè)函數(shù),這個(gè)函數(shù)返回JSX元素亡容。