4, Other ways of writing mapDispatchToProps
MapDispatchToProps can be objects or functions
Writing a:
// The method maps to props
let mapDispatchToProps = {
add: () = > {
return { type: 'add'}},minus: () = > {
return { type: 'sub'}}},Copy the code
Method 2:
const mapDispatchToProps = (dispatch) = > {
const creators = {
add: () = > {
dispatch({ type: 'add'})},minus: () = > {
dispatch({ type: 'sub'}})},return{ dispatch, ... creators, } }` `The react-Redux built-in provider provides a store for Connet components to accessCopy the code
import React from ‘react’ import { Provider } from ‘react-redux’ import store from ‘./store’ import RReduxpage from ‘./index’ // is the component mentioned above
export default function ReactReduxPage() { return (
# # 4, and other written about mapDispatchToProps mapDispatchToProps can is a function object can be written: a ` ` ` js / / method is mapped to the props let mapDispatchToProps = {the add: () => { return { type: 'add' } }, minus: () => { return { type: 'sub' } }, }Copy the code
Method 2:
const mapDispatchToProps = (dispatch) = > {
const creators = {
add: () = > {
dispatch({ type: 'add'})},minus: () = > {
dispatch({ type: 'sub'}})},return{ dispatch, ... creators, } }Copy the code
// Write three functions
import { bindActionCreators } from 'redux'
// write three function implementation principle
export function bindActionCreators(creators, dispatch) {
let obj = {}
for (let key in creators) {
obj[key] = (. args) = > {
constfn = 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), } }Copy the code
The react – redux implementation
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} / >
}
Copy the code