Hands on implementation of react Redux


This article mainly talks aboutreact-reduxAt the same time, better understandingreactApplication of middle and higher order functions

Here the main implementationProviderComponents andconnectFunction, newreact-reduxFolder, which creates a new entry fileindex.jsThrow out the corresponding components and methods

// react-redux/index.js
export {

First usereact-reduxI feel like using itReact.Context, but the internal of the sub component is through thepropsThe data and methods we’ve got hereconnectFunction should have done processing, willstateandactionsAfter repackaging, it is passed to the sub components. Therefore, the first step is to create the context of Redux:

// context.js
import React from "react";
export default React.createContext();

Then createProvider.jsDocument:

import React,{Component} from "react";
import ReduxContext from "./context";

export default class Provider extends Component {
    return (
      <ReduxContext.Provider value={{ store: this.props.store }}>

Provider.jsGet the store from the parent component and give it to the provider for easy downward transmission. Then, render the child component.

Next, createconnect.jsconnectReturns a function and receives the rendered component:

export default function (mapStateToProps,mapDispatchToProps){
    return function(WrapperComponent){}

We know that the returned function is also thrown after execution, so the returned function should be aComponent classOr oneFunction componentIt’s used hereComponent classIt is more appropriate because the update view function of the subscription is also destroyed, and then the store can be passed down through thecontextGot:

import ReduxContext from './context'
import React, { Component } from 'react'
export default function (mapStateToProps, mapDispatchToProps) {
  return function (WrapperComponent) {
    return class extends Component {
      static contextType = ReduxContext
      constructor(props, context) {
        //Return the wrapped state through mapstatetoprops. Here, users can get the desired state and optimize the rendered components
        this.state = mapStateToProps(context.store.getState())
      componentDidMount() {
          //Subscribe to update view
        this.unSubscribe = this.context.store.subscribe(() => {
      componentWillUnmount() {

renderIn this way, the values in the store and the processed actions can be passed to the sub components by passing the parameters

render() {
  //Handle binding action
  let actions = redux.bindActionCreator(mapDispatchToProps,this.context.store.dispatch);
  return <WrapperComponent {...this.state} {...actions} />