Includes only the main API, welcome correction!

First, react-redux and Redux libraries have the following apis

React-redux consists of two main components:

  • Provider <Provider store>
Usage:<Provider store>Make the component hierarchyconnect()Methods all get the Redux store. Normally, your root component should be nested in<Provider>In order to useconnect()Methods.
How to do it: Put store on content
  • connect connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])
Usage: connectThe React componentswithRedux store. The wire operation does not change the original component class. Returns a new one withRedux storeConnected component classes.

MapStateToProps: Place the state obtained from content on the props If you specify this parameter, you will get the result of executing the mergeProps

Redux includes:

  • action: A collection of all operations
  • dispatchPush action to createStore
  • createStore: provides methods to get state and dispatch,middleWareExecution is also in this phase
  • middleware: provides intermediate operations for the Dispatch process, with all dispatch operations going through the middleware
Common middleware writing
function logger({ getState }) {
  return (next) => (action) => {
    console.log('will dispatch', action) // call the dispatch of the next middleware in the middleware chain.let returnValue = next(action)

    console.log('state after dispatch', getState()) // Will be the action itself, unless // middleware modifies it.return returnValue
  }
}
Copy the code

Middleware is a nested high-level function that takes getState next Action and returns next(Action).

Monkeypatch writing
function logger(store) {
  let next = store.dispatch

  // Previously:
  // store.dispatch = function dispatchAndLog(action) {

  return function dispatchAndLog(action) {
    console.log('dispatching', action)
    let result = next(action)
    console.log('next state', store.getState())
    return result
  }
}
Copy the code
ApplyMiddleware is a simple implementation
function applyMiddlewareByMonkeypatching(store, middlewares) {
  middlewares = middlewares.slice()
  middlewares.reverse()

  // Transform dispatch functionWith each middleware.middlewares. ForEach (Middleware => // Store. Dispatch = Middleware (store)} Store. Dispatch = Middleware (store);Copy the code