深刻理解react-redux

1、react-redux做用

react-redux的做用就是將reactredux鏈接起來,將redux中的store傳遞到react組件中javascript

2、關於展現組件與容器組件的對比

展現組件 容器組件
目的 展示在頁面
是否感知redux
要獲取數據 this.props
要改變數據 調用props中傳入的action
建立者 開發人員

總結一點:展現組件就是react,容器組件是redux鏈接reactjava

3、react-redux的使用

  • 一、安裝react

    npm install react-redux --save
  • 二、react-redux中使用到的方法git

    • 一、Provider實質上就是將store傳遞到容器組件,容器組件又傳遞數據到展現組件github

      <Provider store={store}>
      ...容器組件
      </Provider>
    • 二、connect將容器組件鏈接到展現組件中,進行數據的傳遞npm

      //connect是一個柯里化函數 
      export default connect(xxx)(展現組件)
  • 三、通常咱們利用redux開發react項目常見的項目目錄redux

    這裏寫圖片描述

4、深刻理解connect

  • 一、connect源碼markdown

    connect函數傳遞三個參數,實際開發中通常都是傳入前2個參數ide

    ...
    return function connect(mapStateToProps, mapDispatchToProps, mergeProps) {
    ...
    }
    ...
    • 一、mapStateToProps是一個(函數類型),接收一個完整的redux狀態樹做爲參數,返回當前展現組件須要的狀態樹,返回的key會當作props傳遞到展現組件。
    • 二、mapDispatchToProps是一個(對象或者函數類型),接收一個完整的reduxdispatch方法做爲參數,返回當前組件相關部分的或者所有的action
    • 三、mergeProps是一個(函數類型),若是指定這個函數,分別得到mapStateToPropsmapDispatchToProps返回值以及當前組件的props做爲參數
  • 二、mapStateToProps(state,[ownProps])的解析函數

    第一個參數是必填的,第二個參數是選填的

    • 一、state返回的參數做爲props傳遞到展現組件
    • 二、ownProps表示當前容器組件中的屬性
  • 三、關於mapStateToProps的代碼

    import {connect} from 'react-redux';
    import * as ActionCreators from './../actions';
    import Counter from './../components/Counter';
    
    export default connect(
        /** * 解析:mapStateToProps(state),返回一個counter以props傳遞給Counter組件中 * 關於state.counter1的解析,請參考下面的反向查找流程圖 */
        (state) =>({counter:state.counter1}),
        ActionCreators
    )(Counter);

    這裏寫圖片描述

5、關於connect的寫法

  • 一、mapStateToProps是函數mapDispatchToProps是對象(代碼見上面)
  • 二、mapStateToProps是函數mapDispatchToProps也是函數

    import {connect} from 'react-redux';
    import Counter from './../components/Counter';
    import {onIncrement,onDecrement,incrementIfOdd,incrementAsync} from './../actions';
    
    export default connect(
        state =>({counter:state.counter1}),
        dispatch =>({
            onIncrement:()=>dispatch(onIncrement())
        })
    )(Counter);
  • 三、直接使用裝飾器(不須要單首創建容器組件) 配置ES7的開發環境

    import {connect} from 'react-redux';
    import React, {Component} from 'react';
    import * as ActionCreators from './../actions';
    
    @connect(
        state =>({counter:state.counter1}),
        ActionCreators
    )
    export default class Counter extends Component {
        constructor(props) {
            super(props);
        }
    
        render() {
            const {counter,onIncrement,onDecrement,incrementIfOdd,incrementAsync} = this.props;
            ....
        }

6、代碼下載地址demo

相關文章
相關標籤/搜索