Объясни на русском подробно как тут работает thunk, что за return в нём, почему там…
- User
Объясни на русском подробно как тут работает thunk, что за return в нём, почему там такие параметры, что за функция action, какой флоу данных вообще. thunk.js export const thunkMiddleware = ({ dispatch, getState }) => (next) => (action) => { if (typeof action === 'function') { return action(dispatch, getState); } return next(action); }; store.js import { createStore, combineReducers, applyMiddleware } from 'redux'; import { thunkMiddleware } from './thunk'; import { cardsReducer } from './reducer'; import { authReducer } from './authReducer';
const rootReducer = combineReducers({ cards: cardsReducer, auth: authReducer });
export const store = createStore(rootReducer, applyMiddleware(thunkMiddleware)); reducer.js import { FETCH_CARDS_SUCCESS, FETCH_CARDS_FAILURE } from './actions';
const initialState = { cards: [], error: null };
export const cardsReducer = (state = initialState, action) => { switch (action.type) { case FETCH_CARDS_SUCCESS: return { ...state, cards: action.payload, error: null }; case FETCH_CARDS_FAILURE: return { ...state, error: action.payload }; default: return state; } }; authreducer.js import { LOGIN_SUCCESS, LOGIN_FAILURE } from './actions';
const initialState = { isAuthenticated: false, error: null };
export const authReducer = (state = initialState, action) => { switch (action.type) { case LOGIN_SUCCESS: return { ...state, isAuthenticated: true, error: null }; case LOGIN_FAILURE: return { ...state, isAuthenticated: false, error: action.payload }; default: return state; } }; actions.js export const LOGIN_SUCCESS = 'LOGIN_SUCCESS'; export const LOGIN_FAILURE = 'LOGIN_FAILURE'; export const FETCH_CARDS_SUCCESS = 'FETCH_CARDS_SUCCESS'; export const FETCH_CARDS_FAILURE = 'FETCH_CARDS_FAILURE';
export const loginSuccess = () => ({ type: LOGIN_SUCCESS });
export const loginFailure = (error) => ({ type: LOGIN_FAILURE, payload: error });
export const loginThunk = (username, password) => { return async (dispatch) => { try { const response = await fetch('http://localhost:5000/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) });
if (response.status === 200) { dispatch(loginSuccess()); } else { const { message } = await response.json(); dispatch(loginFailure(message)); } } catch { dispatch(loginFailure('Network error')); } };};
export const fetchCardsSuccess = (cards) => ({ type: FETCH_CARDS_SUCCESS, payload: cards });
export const fetchCardsFailure = (error) => ({ type: FETCH_CARDS_FAILURE, payload: error });
export const fetchCards = (searchTerm = '') => { return async (dispatch) => { try { const response = await fetch( );
- Assistant
- User
Хорошо, но в нашей loginthunk возвращается функция только с 1 параметром - dispatch. А в return action мы передаём 2 параметра. А в случае loginSuccess там вообще нет параметров
- Assistant
Давайте подробнее разберемся с тем, как передаются параметры в thunk и почему это работает.
- User
Вот исходный код thunk. Почему тут в ретёрне 3 параметра, для чего они: import type { Action, AnyAction } from 'redux' import type { ThunkMiddleware } from './types'
export type { ThunkAction, ThunkActionDispatch, ThunkDispatch, ThunkMiddleware, } from './types'
/** A function that accepts a potential "extra argument" value to be injected later,
- and returns an instance of the thunk middleware that uses that value */ function createThunkMiddleware< State = any, BasicAction extends Action = AnyAction, ExtraThunkArg = undefined,
(extraArgument?: ExtraThunkArg) { // Standard Redux middleware definition pattern: // See: https://redux.js.org/tutorials/fundamentals/part-4-store#writing-custom-middleware const middleware: ThunkMiddleware<State, BasicAction, ExtraThunkArg> = ({ dispatch, getState }) => next => action => { // The thunk middleware looks for any functions that were passed to . // If this "action" is really a function, call it and return the result. if (typeof action === 'function') { // Inject the store's and methods, as well as any "extra arg" return action(dispatch, getState, extraArgument) }
- Assistant