接着上一篇講,上一篇咱們實現了本身的Redux和介紹了React的context以及Provider的原理。react
Provider組件主要有如下下兩個做用redux
首先咱們要知道,Provider組件的任務是將stroe傳遞給子組件,它只是一個傳遞數據的組件,只須要將子組件展現出來就好。ide
import React from 'react' import PropTypes from 'prop-types' export class Provider extends React.Component{ static childContextTypes = { store: PropTypes.object } getChildContext(){ return {store:this.store} } constructor(props, context){ super(props, context) this.store = props.store } render(){ return this.props.children } }
connect的做用就是將React和Redux中的store鏈接起來函數
首先要明確它的任務:this
根據它的任務就能知道,它是一個高階函數spa
官方給出connect的定義:code
connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])
很是好理解了,在React-Redux中,咱們經常使用的就是前兩個參數。component
這個函數幫助咱們將store中的數據做爲props傳遞給組件,也就是實現了connect方法的第一個任務中間件
mapStateToProps(state, ownProps) : stateProps
咱們常常這麼使用mapStateToProps對象
state=>({ num: state})
或者這樣只獲取咱們當前須要的屬性
const mapStateToProps = (state) => { return { num: state.num } }
這個函數的會將action以props的形式傳遞給組件,組件可用this.props觸發相應action,也就是完成了上面的第二個任務。
mapDispatchToProps(dispatch, ownProps): dispatchProps
這個函數返回的是裝有action的對象,一般咱們直接給它賦值成一個對象,再把咱們的action放進去。
import { add, remove, addAsync } from './index.redux' mapDispatchToProps = { add, remove, addAsync }
從這裏看好像是完成了咱們的任務,可是注意:在咱們的組件能夠經過this.props觸發相應的action,可是尚未dispatch,因此只返回了一個type,因此上面的代碼並非正確的,只是便於你們理解。
咱們還須要dispatch一下action,下面纔是正確的代碼:
const mapDispatchToProps = (dispatch, ownProps) => { return { add: (...args) => dispatch(actions.add(...args)), remove: (...args) => dispatch(actions.remove(...args)), addAsync: (...args) => dispatch(actions.addAsync(...args)) } }
有人會問,我用React-Redux的connect時,這個參數直接穿的是action對象呀,怎麼回事?
這是由於在connect內部使用了Redux提供的bindActionCreators方法,在connect內部將全部的action都dispatch了。咱們實現的時候,也須要實現這個bindActionCreators方法。
mergeProps顧名思義,就是將stateProps、dispatchProps、ownProps合併起來。
若是不指定mergeProps,默認用Object.assign
function mergeProps(stateProps, dispatchProps, ownProps) { return Object.assign({}, ownProps, { num: stateProps.num, add: () => dispatchProps.add(), remove: () => dispatchProps.remove(), addAsync: () => dispatchProps.addAsync(), }) }
規定connector的行爲,一般咱們使用默認值。
咱們常見的寫法,也就是ES7的decorator裝飾器,也就是裝飾者模式,這種寫法比較簡便:
@connect( state=>({ num: state}), { add, remove, addAsync } ) class App extends React.Component{ render(){ return ( <div> <h2>如今有物品{this.props.num}件</h2> <button onClick={this.props.add}>add</button> <button onClick={this.props.remove}>remove</button> <button onClick={this.props.addAsync}>addAsync</button> </div> ) } } export default App;
或者是更容易理解的高階函數的寫法:
class App extends React.Component{ render(){ return ( <div> <h2>如今有物品{this.props.num}件</h2> <button onClick={this.props.add}>add</button> <button onClick={this.props.remove}>remove</button> <button onClick={this.props.addAsync}>addAsync</button> </div> ) } } App = connect( state => ({num: state), { add, remove, addAsync } )(App)
第二中寫法咱們能夠更好的理解connect函數如何工做:connect接受了它的四個參數,而後返回了一個高階組件,高階組件須要接收一個組件做爲參數,在高階組件中經過處理被傳入的組件,其中用到了connect的四個參數,最後將處理後的組件返回出去。
connect方法返回了一個函數,函數裏返回了一個組件,有兩次返回,這裏咱們用兩層箭頭函數:
export const connect = (mapStateToProps = (state) => state, mapDispatchToProps={}) => (WrapComponent) => { return class ConnectComponent extends React.Component{ } }
它等價於這種寫法:
export function connect (mapStateToProps = (state) => state, mapDispatchToProps={}) { return function (WrapComponent) { return class ConnectComponent extends React.Component{ } } }
雙層箭頭函數更加簡潔,也算是編寫高階函數的一個技巧吧。
mapStateToProps的任務已經明確,先接收一個,獲取Redux中的store,將stroe經過props傳遞給組件,代碼以下:
import React from 'react' import PropTypes from 'prop-types' export const connect = (mapStateToProps = (state) => state, mapDispatchToProps={}) => (WrapComponent) => { return class ConnectComponent extends React.Component{ static contextTypes = { store: PropTypes.object } constructor (props, context) { super(props, context) this.state = { props: {} } } componentDidMount () { const {store} = this.context this.update() store.subscribe(()=>this.update()) } update () { const { store } = this.context const stateProps = mapStateToProps(store.getState()) this.setState({ props: { ...this.state.props, ...stateProps } }) } render () { return <WrapComponent {...this.props}/> } } }
很明確,咱們先用context獲取了Provider組件傳遞過來的store而後將this.props與store中的屬性merge成一個新的this.props傳遞給組件,組件mount的時候用store.subscribe監聽了store內數據的變化,從而實時通知組件,完成了connect的第四個任務。
介紹mapDispatchToProps的是有也說了,傳遞進來的action不能直接使用,須要dispatch一下,Redux提供了一個bindActionCreators方法,一樣咱們也在本身的Reudx中實現這個方法。
接着上面的代碼來寫
import React from 'react' import PropTypes from 'prop-types' import {bindActionCreators} from './myRedux' export const connect = (mapStateToProps=state=>state,mapDispatchToProps={})=>(WrapComponent)=>{ return class ConnectComponent extends React.Component{ static contextTypes = { store:PropTypes.object } constructor(props, context){ super(props, context) this.state = { props:{} } } componentDidMount(){ const {store} = this.context store.subscribe(()=>this.update()) this.update() } update(){ const {store} = this.context const stateProps = mapStateToProps(store.getState()) const dispatchProps = bindActionCreators(mapDispatchToProps, store.dispatch) this.setState({ props:{ ...this.state.props, ...stateProps, ...dispatchProps } }) } render(){ return <WrapComponent {...this.state.props}></WrapComponent> } } }
這個很簡單,主要的就是bindActionCreators方法,寫在咱們本身的Redux中
function bindActionCreator(creator, dispatch){ return (...args) => dispatch(creator(...args)) } export function bindActionCreators(creators, dispatch){ return Object.keys(creators).reduce((ret,item)=>{ ret[item] = bindActionCreator(creators[item],dispatch) return ret },{}) }
也不是很難理解,遍歷對象中的全部action,每一個action都dispatch一下,返回每個dispatch以後的action。
好比以前的add方法爲:add(args),如今的add方法是:store.dispatch(add(args))
如今咱們的Provider組件和connect高階函數已經實現,下一篇咱們實現Redux的中間件。