1.2.3. dva
什么是dva,解决了什么痛点
- dva 首先是一个基于 redux 和 redux-saga 的数据流方案,然后为了简化开发体验,dva 还额外内置了 react-router 和 fetch,所以也可以理解为一个轻量级的应用框架。
- 组件之间的通信:React组件对于父子,兄弟之间的通信,只能通过传参完成,对于大型应用,不太方便。
- 数据流:数据如何与视图串联起来?路由和数据如何绑定?如何编写异步逻辑等?
- 没有用dva之前的数据流方案比较复杂,要引入多个第三方的库:
- 路由:react-router
- 架构: redux
- 异步操作:redux-saga 引入dva后,把上面三个进行了工具库包进行包装,简化了api,让开发变得更容易。
阐述Model对象的基本组成及其作用
Model对象定义组成:
- namespace:
- state: 数据结构变量的声明
- reducers:纯函数集 (即通过action改变state),定义同步action动作
- effects:异步函数集,定义异步action动作
- subscriptions: 订阅函数集
app.model({
namespace: 'count',
state: {
record: 0,
current: 0,
},
reducers: {
add(state) {
const newCurrent = state.current + 1;
return { ...state,
record: newCurrent > state.record ? newCurrent : state.record,
current: newCurrent,
};
},
minus(state) {
return { ...state, current: state.current - 1};
},
},
effects: {
*add(action, { call, put }) {
yield call(delay, 1000);
yield put({ type: 'minus' });
},
},
subscriptions: {
keyboardWatcher({ dispatch }) {
key('⌘+up, ctrl+up', () => { dispatch({type:'add'}) });
},
},
});
@umijs/plugin-dva的启用条件是什么
配置成功启动
dva-loading的实现原理
调用dva-loading,使其返回的extraReducers和onEffect关联到dva其他组件和方法,然后通过onEffect关联的方法触发onEffect方法,通过3个yield完成loading显隐和数据操作。值得一提的是,触发onEffect的时候,yield put会触发extraReducers,通过redux-saga管理最终的显隐状态