Análisis de código fuente de Redux - 5, principio de acción asíncrono

Directorio de artículos

reaccionar-thunk

El código fuente es demasiado corto:

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. Middleware estándar de React.

Todo es código fijo.

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

2. Si la Acción es una función, llámala; de lo contrario, déjala pasar.

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

return next(action)

En resumen, los procesadores solo admiten acciones funcionales.

por ejemplo

Acción en caso contrario:

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

Cuando el thunk recibe esta Acción, la llamará directamente. Ejecute el código asíncrono interno.

El problema final es una Acción síncrona.

Supongo que te gusta

Origin blog.csdn.net/qq_37284843/article/details/123651443
Recomendado
Clasificación