一、 dva的核心概念
-
State:一个对象,保存整个应用状态
-
View:React组件构成的视图层
-
Action:一个对象,用来描述 UI 层事件
-
connect方法:一个函数,绑定State到View
-
dispatch方法:一个函数,发送Action到State
State 和 View
State 是储存数据的地方,收到 Action 以后,会更新数据。
View 就是 React 组件构成的 UI 层,从 State 取数据后,渲染成 HTML 代码。只要 State 有变化,View 就会自动更新。
Action 是用来描述 UI 层事件的一个对象。
{
type: ‘click-submit-button’,
payload: this.form.data
}
connect 方法 是一个函数,绑定 State 到 View。
import { connect } from 'dva';
function mapStateToProps(state) {
return { todos: state.todos };
}
connect(mapStateToProps)(App);
connect 方法返回的也是一个 React 组件,通常称为容器组件。因为它是原始 UI 组件的容器,即在外面包了一层 State。
connect 方法传入的第一个参数是 mapStateToProps 函数,mapStateToProps 函数会返回一个对象,用于建立 State 到 Props 的映射关系。
dispatch 方法
dispatch 是一个函数方法,用来将 Action 发送给 State。
dispatch({
type: ‘click-submit-button’,
payload: this.form.data
})
dispatch 方法从哪里来?被 connect 的 Component 会自动在 props 中拥有 dispatch 方法。
Reducer函数
Reducer 是 Action 处理器,用来处理同步操作,可以看做是 state 的计算器。它的作用是根据 Action,从上一个 State 算出当前 State。
- 该函数把一个集合归并成一个单值。
type Reducer<S, A> = (state: S, action: A) => S
写法:
reducers:{
'delete'(state, { payload: id }) {
return state.filter(item => item.id !== id);
}
}
//delete会被解析为字符串=>
reducers:{
delete:function(state, { payload: id }){
return state.filter(item => item.id !== id);
}
}
Effects
Action 处理器,处理异步动作,基于 Redux-saga 实现。Effect 指的是副作用。根据函数式编程,计算以外的操作都属于 Effect,典型的就是 I/O 操作、数据库读写。
Effect 是一个 Generator 函数,内部使用 yield 关键字,标识每一步的操作(不管是异步或同步)。
function *addAfter1Second(action, { put, call }) {
yield call(delay, 1000);
yield put({ type: 'add' });
}
dva 提供多个 effect 函数内部的处理函数,比较常用的是 call 和 put。
call:执行异步函数
put:发出一个 Action,类似于 dispatch
二、Model中的常用属性:
state:
namespace:
reducers:
effects:
subscriptions: