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一下 謝謝

 

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