dva框架之redux相关

dva封装了redux,减少很多重复代码比如action reducers 常量等,本文简单介绍dva redux操作流程。

利用官网的一个加减操作小实例来操作:

dva所有的redux操作是放在models目录下,通过namespace作为key,标识不同的模块state。

可以给state设置初始数据,比如:

reducers跟传统的react-redux写法一致,所有的操作放在reducers对象内:

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'

异步操作写在effects对象内:

effects: {
    *asyncDecr({ payload }, { call, put }) {
      yield call(delay, 1000);
      yield put({type: 'decrement' });
    }
  },

其实*asyncDecr 就是function* asyncDecr,是个Generator状态机 

call, put其实是saga的写法,dva集成了saga。

UI组件内的使用:

引入连接器:

import { connect } from 'dva';
利用connect连接器将mapStateToProps 导入组件:
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> */}
          &nbsp;&nbsp;
          <Button type="primary">decr</Button>
        </div>
      </div>
    );
  }

小栗子源码链接:

https://github.com/qjhe/dva-demo  如果感觉还有点作用,请顺手star一下 谢谢

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章