dva封装了redux,减小不少重复代码好比action reducers 常量等,本文简单介绍dva redux操做流程。react
利用官网的一个加减操做小实例来操做:git
dva全部的redux操做是放在models目录下,经过namespace做为key,标识不一样的模块state。github
能够给state设置初始数据,好比:redux
reducers跟传统的react-redux写法一致,全部的操做放在reducers对象内:app
reducers: { 'increment'(state, action) { return { counter: state.counter + 1 } }, decrement(state, action) { return { counter: state.counter - 1 } } }
写法能够为'increment' 加引号,也能够直接increment 不加引号,如上面代码中 decrement异步
推荐加引号写法,能够作为功能或状态区分 如: 'fecth/fetching' 'fetch/fail' 'fetch/success'async
异步操做写在effects对象内:fetch
effects: { *asyncDecr({ payload }, { call, put }) { yield call(delay, 1000); yield put({type: 'decrement' }); } },
其实*asyncDecr 就是function* asyncDecr,是个Generator状态机 this
call, put实际上是saga的写法,dva集成了saga。spa
UI组件内的使用:
引入链接器:
import { connect } from 'dva';
const mapStateToProps = (state) => { return { products: state.products, }; }; export default connect(mapStateToProps)(ProductPage);
如今能够直接取出对象:
const { products, dispatch } = this.props;
render() { const { products, dispatch } = this.props; return ( <div className={styles.wrapper}> <div className={styles.title}>结果 {products.counter}</div> <div> <Button type="primary" onClick={()=>dispatch({type:'products/increment',payload:1})}>incr</Button> <Button type="primary" onClick={()=>dispatch({type:'products/asyncDecr',payload:1})}>incr</Button> {/* <Button type="primary">incr</Button> */} <Button type="primary">decr</Button> </div> </div> ); }
小栗子源码连接:
https://github.com/qjhe/dva-demo