getState 和 dispatch 是如何导入到 redux-thunk action creator 中的?

How are getState and dispatch imported in redux-thunk action creator?

import _ from 'lodash';
import jsonPlaceholder from '../apis/jsonPlaceholder';

export const fetchPostsAndUsers = () => async (dispatch, getState) => {
  await dispatch(fetchPosts());

  _.chain(getState().posts)
    .map('userId')
    .uniq()
    .forEach(id => dispatch(fetchUser(id)))
    .value();
};

export const fetchPosts = () => async dispatch => {
  const response = await jsonPlaceholder.get('/posts');

  dispatch({ type: 'FETCH_POSTS', payload: response.data });
};

在上面的代码中,getState 和 dispatch 函数作为参数传递给 action creator 函数,我不解的是为什么这些函数没有从任何地方导入或者 react/redux 以某种方式为我们导入它们?

好的,我会尽力消除你的困惑, 如您所知,action creators returns 普通 javascript 对象,但是 thunk 是一个中间件,它允许您 return 函数而不是来自 action creators 的普通 javascript 对象,所以当如果你 return plain javascript 对象来自 action creator 它以正常方式处理,你使用 thunk,但是当你 return a 来自 action creator 的 function 而不是 thunk 处理它并使用 dispatchgetState 调用此函数,因此您可以异步调度 action,你没有传递这些参数,这样看你是 return 从 action creator 调用 回调 并用这些参数调用这个回调。

希望对您有所帮助。

当您使用 redux 提供的连接函数将 react 组件与 redux 连接时,您将传入函数:mapStateToProps 和 mapDispatchToProps。这些将是您要查找的参数(dispatch 和 getState)。

Thunk 是一个可选地接受一些参数的函数和 returns 另一个函数,它接受 dispatch 和 getState 函数,这两个都是由 Redux Thunk 中间件提供的