React-redux has been in use for more than two years since 2016. Redux/React-Redux/React-redux/React-Redux/React-Redux/React-Redux/React-Redux Write down the main points briefly, on the one hand for the reference of interested readers, on the other hand for your own summary.

redux

The core of React-Redux is redux. With redux built-in, react-Redux provides only a few apis to associate redux and React components and react state updates.

First, take a look at how to use Redux. Redux old driver can just slide the wheel to the next chapter. In a nutshell, redux has three concepts: Action, Reducer and Dispatch. Action and Dispatch are easier to understand: action instructions and submit action instruction methods. Reducer, although I do not understand it literally, can be understood as a function used to generate state at the level of abstraction. A simple example illustrates these three concepts:

// action
const INCREMENT = { type: 'INCREMENT' }

// reducer
function count( state = 0, action ) {
    switch( action.type ) {
        case 'INCREMENT':
            return state + 1
        default: 
          return state
    }
}

// dispatch
// Start using redux here
const store = redux.createStore( count )
console.log( store.getState() )  / / 0
store.dispatch( INCREMENT )
console.log( store.getState() ) / / 1
Copy the code

There are two modules in Redux:

  • storeobject
  • The middleware

Store object

APIcreateStore creates a store object, which does two things:

  1. Initialize the state
  2. Exposed interfaces:getState().dispatch( action ).subscribe( listener )And so on. Among themgetState()To get the real-time state in the store,dispatch(action)Update state based on incoming action,subscribe( listener)You can listen for state changes.

The middleware

Middleware can be used to debug or submit asynchronous action instructions. When we initialized the store, we added multiple middleware via createStore(Reducer, state, applyMiddleware(Middleware1, Middleware2)). To implement multiple middleware, Redux specifically introduces the compose() method of functional programming. In short, compose makes writing multilayer function calls elegant:

// The compose method is not used
a( b( c( 'd')))// Compose method
compose( a, b, c )('d')
Copy the code

The middleware writing method is more peculiar, is multi-level function, when reading the source code around a bit. Obviously, the middleware writing can be optimized, and while it’s easy to use in source code, it’s a little more complicated for Redux users to use, with single-layer functions.

function logMiddleware({ getState }) {
    return nextDispatch= > action => {
        console.log( 'before dispatch', getState() )
        const res = nextDispatch( action )
        console.log( 'after dispatch', getState() )
        return res
    }
}
Copy the code

react-redux

Now that you know how Redux works, you can see how most use scenarios of React-Redux work. React – Redux provides several apis to associate Redux with React.

Use of react-redux based on the previous example:

// action
const increment = (a)= > ({ type: 'INCREMENT' })

// reducer
function count( state = 0, action ) {
    switch( action.type ) {
        case 'INCREMENT':
            return state + 1
        default: 
          return state
    }
}

// redux
const store = Redux.createStore( count )

// react-redux
const { Provider, connect } = ReactRedux
const mapStateToProps = state= >({count: state } )
const mapDispatchToProps = dispatch= >({increment : (a)= > dispatch( increment() ) } )
const App = connect( mapStateToProps, mapDispatchToProps )( class extends React.Component {
  onClick = (a)= > {
   this.props.increment()
  }  
  render() {
        return <div>
          <p>Count: { this.props.count }</p>
          <button onClick={ this.onClick} >+</button>
        </div>
    }
} )

ReactDOM.render( <Provider store={ store} >
    <App />
</Provider>.document.getElementById( 'app'))Copy the code

Click to run the case

The two most commonly used apis provided by React-Redux are:

  • Provider
  • connect

Provider

The Provider is essentially a React component that mounts state in the Redux Store through the React Context API, which enables a component to pass props across multiple levels of components, and starts listening for state when the component is initialized. When listening for a state change, the Provider will reset the storeState on the context.

class Provider extends Component {
    constructor(props) {
      super(props)
    
      const { store } = props
    
      this.state = {
        storeState: Redux.store.getState(),
      }
    }
    
    componentDidMount() {
      this.subscribe()
    }
    
    subscribe() {
        const { store } = this.props
        store.subscribe(() => {
          const newStoreState = store.getState()
          this.setState(providerState => {
            return { storeState: newStoreState }
          })
        })
    }
    render() {
        const Context = React.createContext(null)
        <Context.Provider value={this.state}>
            {this.props.children}
        </Context.Provider>
    }
}
Copy the code

connect()

The Connect method assigns some or all of the state and submit action instruction methods to the React component props via connectHOC (HOC: React high-level component).

summary

Writing React without Redux is like writing code without Git. We need redux to better manage state in our React application. Understanding how REdux/React-Redux works will eliminate the unknowns and puzzles of redux development, and create a complete code execution loop in your mind, making the development process transparent and intuitive.

If this article helped you, I am honored too. Please like it and bookmark it. If you have any questions or suggestions, feel free to post them in the comments section below.