dva框架之redux相關

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';
利用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

相關文章
相關標籤/搜索