Redux source code analysis - 5, asynchronous Action principle

Article directory

react-thunk

The source code is too short:

const middleware: ThunkMiddleware<State, BasicAction, ExtraThunkArg> =
  ({
    
     dispatch, getState }) =>
  next =>
  action => {
    
    
    // The thunk middleware looks for any functions that were passed to `store.dispatch`.
    // If this "action" is really a function, call it and return the result.
    if (typeof action === 'function') {
    
    
      // Inject the store's `dispatch` and `getState` methods, as well as any "extra arg"
      return action(dispatch, getState, extraArgument)
    }

    // Otherwise, pass the action down the middleware chain as usual
    return next(action)
  }
return middleware

1. Standard React middleware.

It's all fixed code.

const middleware: ThunkMiddleware<State, BasicAction, ExtraThunkArg> =
  ({
    
     dispatch, getState }) =>
  next =>
  action => {
    
    
		//...
  }
return middleware

2. If the Action is a function, call it, otherwise let it go.

if (typeof action === 'function') {
    
    
  return action(dispatch, getState, extraArgument)
}

return next(action)

In short, thunks just support functional Actions.

for example

Action in counter case:

export const Normal = v => ({
    
    
	type: "Normal", amount: v
})
export const Async = (v, time) => {
    
    
	return (dispatch) => {
    
    
		setTimeout(() => {
    
    
			dispatch(Normal(v));
		}, time);
	}
}

When the thunk receives this Action, it will call it directly. Execute the inner asynchronous code.

The final issue is a synchronous Action.

Guess you like

Origin blog.csdn.net/qq_37284843/article/details/123651443