繁体   English   中英

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 函数作为 arguments 传递给动作创建者 function,令我困惑的是为什么这些函数没有从任何地方导入,或者 react/redux 以某种方式为我们导入它们?

ok I will try to clear your confusion, As you know action creators returns plain javascript object, but thunk is a middleware which allows you to return function instead of plain javascript object from the action creators, so when you use thunk if you return plain javascript object from action creator its handled in normal way, but when you return a function from action creator than thunk handle it and call this function with dispatch and getState , so you can dispatch an action asynchronously, you are not passing these arguments, see it this您从动作创建者返回回调并 thunk 使用这些 arguments 调用此回调的方式。

希望能帮助到你。

当您使用 redux 提供的连接 function 将反应组件与 redux 连接时,您将传递给函数: mapStateToProps 和 mapDispatchToProps 这些将是您要查找的参数(调度和 getState)。

Thunk 是一个 function,它可以选择接受一些参数并返回另一个 function,它接受 dispatch 和 getState 函数,这两个函数都由 Redux Thunk 中间件提供

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM