簡體   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