04 - react-redux使用及原理-02

179 阅读1分钟

4、 关于 mapDispatchToProps的其他写法

mapDispatchToProps 可以是对象可以是函数

写法一:

// 方法映射到props
let mapDispatchToProps = {
  add: () => {
    return { type: 'add' }
  },
  minus: () => {
    return { type: 'sub' }
  },
}

写法二:

const mapDispatchToProps = (dispatch) => {
  const creators = {
    add: () => {
      dispatch({ type: 'add' })
    },
    minus: () => {
      dispatch({ type: 'sub' })
    },
  }
  return {
    dispatch,
    ...creators,
  }
}
```## 3、除此之外还需要 提供store 让 connet组件可以取到

通过 react-redux 内置 的provider 提供 store

import React from 'react' import { Provider } from 'react-redux' import store from './store' import RReduxpage from './index' // 就是上述的组件

export default function ReactReduxPage() { return (

) }




## 4、 关于 mapDispatchToProps的其他写法

mapDispatchToProps 可以是对象可以是函数

写法一:


```js
// 方法映射到props
let mapDispatchToProps = {
  add: () => {
    return { type: 'add' }
  },
  minus: () => {
    return { type: 'sub' }
  },
}

写法二:

const mapDispatchToProps = (dispatch) => {
  const creators = {
    add: () => {
      dispatch({ type: 'add' })
    },
    minus: () => {
      dispatch({ type: 'sub' })
    },
  }
  return {
    dispatch,
    ...creators,
  }
}

// 写法三 函数

import { bindActionCreators } from 'redux'

// 写法三 函数 实现原理
export function bindActionCreators(creators, dispatch) {
  let obj = {}
  for (let key in creators) {
    obj[key] = (...args) => {
      const fn = creators[key]
      dispatch(fn(...args))
    }
  }
  return obj
}

const mapDispatchToProps = (dispatch) => {
  const creators = {
    add: () => {
      return { type: 'add' }
    },
    minus: () => {
      return { type: 'sub' }
    },
  }
  return {
    dispatch,
    ...bindActionCreators(creators, dispatch),
  }
}





react-redux 实现

import React, { useContext, useEffect, useReducer, useState } from 'react'
import { bindActionCreators } from './util'
const Content = React.createContext()

export function Provider({ store, children }) {
  return <Content.Provider value={store}>{children}</Content.Provider>
}

export const connect =
  (mapToProps, mapDispatchToProps) => (WrappedComponent) => (props) => {
    const store = useContext(Content)
    const stateProps = store ? mapToProps(store.getState()) : {}
    let dispatchProps =
      typeof mapDispatchToProps === 'function'
        ? mapDispatchToProps(store.dispatch)
        : bindActionCreators(mapDispatchToProps, store.dispatch)

    const [ignore, forceUpdate] = useReducer((x) => x + 1, 0)

    useEffect(() => {
      const fn = store.subscribe(() => {
        forceUpdate()
      })
      return () => {
        fn()
      }
    }, [store])

    return <WrappedComponent {...props} {...stateProps} {...dispatchProps} />
  }