react-redux
做用
react-redux
的做用就是將react
與redux
鏈接起來,將redux
中的store
傳遞到react
組件中javascript
展現組件 | 容器組件 |
---|---|
目的 | 展示在頁面 |
是否感知redux | 否 |
要獲取數據 | this.props |
要改變數據 | 調用props中傳入的action |
建立者 | 開發人員 |
總結一點:展現組件就是
react
,容器組件是redux
鏈接react
的java
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
connect
一、connect
源碼markdown
connect函數傳遞三個參數,實際開發中通常都是傳入前2個參數ide
...
return function connect(mapStateToProps, mapDispatchToProps, mergeProps) {
...
}
...
mapStateToProps
是一個(函數類型),接收一個完整的redux
狀態樹做爲參數,返回當前展現組件須要的狀態樹,返回的key
會當作props
傳遞到展現組件。mapDispatchToProps
是一個(對象或者函數類型),接收一個完整的redux
的dispatch
方法做爲參數,返回當前組件相關部分的或者所有的的action
mergeProps
是一個(函數類型),若是指定這個函數,分別得到mapStateToProps
、mapDispatchToProps
返回值以及當前組件的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);
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;
....
}