为什么我可以在不使用Redux存储实例(store.create())的情况下执行dispatch()方法



我在一些项目中使用了Redux,遵循了一些教程,为了进行API调用(编写返回函数而不是操作的操作创建者(,我们使用redux-thunk.

我不明白为什么在这个动作创建者函数中,我可以运行dispatch()而不必使用存储store.dispatch()的实例?

关于redux文档的示例:

import { createStore } from 'redux'
const store = createStore(todos, ['Use Redux'])
function addTodo(text) {
return {
type: 'ADD_TODO',
text
}
}
store.dispatch(addTodo('Read the docs'))
store.dispatch(addTodo('Read about the middleware'))

教程代码:

const loadRockets = () => async (dispatch) => {
const res = await fetch(URL);
const data = await res.json();
const state = data.map((rocket) => ({
id: rocket.id,
name: rocket.rocket_name,
image: rocket.flickr_images[0],
type: rocket.rocket_type,
description: rocket.description,
reserved: false,
}));
dispatch({ type: LOAD, state });
};

您可以这样做,因为redux-thunk中间件就是这样设计的。如果您调度一个函数,redux-thunk将调用该函数并将调度函数传递给您。如果你很好奇,下面是他们实现的代码(特别是return action(dispatch, getState, extraArgument)部分(:

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 `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
}

https://github.com/reduxjs/redux-thunk/blob/master/src/index.ts#L30

相关内容

最新更新