Redux和React-Redux的實現(二):Provider組件和connect的實現


接着上一篇講,上一篇我們實現了自己的Redux和介紹了React的context以及Provider的原理。

1. Provider組件的實現


Provider組件主要有以下下兩個作用

  1. 在整個應用上包一層,使整個應用成為Provider的子組件
  2. 接收Redux的store作為props,通過context對象傳遞給子組件,所有的子組件都可以取得store

首先我們要知道,Provider組件的任務是將stroe傳遞給子組件,它只是一個傳遞數據的組件,只需要將子組件展示出來就好。

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
	}
}

2. connect方法


connect的作用就是將React和Redux中的store連接起來

首先要明確它的任務:

  1. 接收一個組件,將Redux中的store通過props傳遞給組件
  2. 將Redux中的action也通過props傳遞給組件
  3. 返回一個新的組件,這個組件可以通過this.props訪問到store中的屬性,也可能是觸發action
  4. 當store中的數據發生變化的時候,通知新的組件

根據它的任務就能知道,它是一個高階函數

connect方法定義

官方給出connect的定義:

connect([mapStateToProps],  [mapDispatchToProps],  [mergeProps],  [options])

非常好理解了,在React-Redux中,我們常用的就是前兩個參數。

mapStateToProps

這個函數幫助我們將store中的數據作為props傳遞給組件,也就是實現了connect方法的第一個任務

mapStateToProps(state, ownProps) : stateProps
  1. mapStateToProps的第一個參數就是Redux的store
  2. 第二個參數就是自己的props,也可已將自己的props和store merge到一起傳遞給組件

我們經常這么使用mapStateToProps

state=>({ num: state})

或者這樣只獲取我們當前需要的屬性

const mapStateToProps = (state) => {
  return {
    num: state.num
  }
}

mapDispatchToProps

這個函數的會將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

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(),
  })
}

options

規定connector的行為,通常我們使用默認值。

connect方法的使用

我們常見的寫法,也就是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的四個參數,最后將處理后的組件返回出去。

3. mapStateToProps的實現


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的第四個任務。

4. mapDispatchToProps的實現


介紹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的中間件。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM