zoukankan      html  css  js  c++  java
  • 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 

  • 相关阅读:
    [go]go addressable 详解
    [go]灵活的处理json与go结构体
    [django]django内置的用户模型
    [go]文件读写&io操作
    *2.3.2_加入env
    UVM_INFO
    uvm_config_db在UVM验证环境中的应用
    *2.2.4 加入virtual interface
    *2.2.3 加入objection机制
    2.2.2 加入factory机制
  • 原文地址:https://www.cnblogs.com/juexin/p/9394612.html
Copyright © 2011-2022 走看看