简体   繁体   中英

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 });
};

In the above code getState and dispatch functions are passed as arguments to the action creator function, what im puzzled about is why are these functions not imported from anywhere or does react/redux somehow import them for us?

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 way that you are returning a callback from action creator and thunk call this callback with these arguments.

Hope it helps.

When you connect a react component with redux using a connect function provided by redux you will pass in to functions: mapStateToProps and mapDispatchToProps. Those will be the parameters your looking for (dispatch and getState).

Thunk is a function which optionally takes some parameters and returns another function, it takes dispatch and getState functions, and both of these are supplied by Redux Thunk middleware

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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