如果 StackOverflow 上有類似的問題,我深表歉意,但經過 3 個小時的搜索,我找不到一個。
我正在嘗試學習 Redux 并通過 ReactJS 的初學者熟練程度,并具有以下 thunk 功能:
export const listProducts = () => async (dispatch) => {
try{
dispatch({ type:PRODUCT_LIST_REQUEST })
const { data } = await axios.get('/api/products/')
dispatch({ type:PRODUCT_LIST_SUCCESS, payload: data })
}catch(error){
dispatch({
type:PRODUCT_LIST_FAIL,
payload: misc_data_here
})
}}
此函式在dispatch具有相關代碼的函式內的另一個檔案中被呼叫,如下所示:
function HomeScreen() {
const dispatch = useDispatch()
const productList = useSelector(state => state.productList)
const { error, loading, products } = productList
useEffect(() => {
dispatch(listProducts())
}, [dispatch])
return (rest of UI...]
我的問題如下:
listProducts在這種情況下,redux究竟是如何呼叫的?listProducts()(dispatch function here)如果我的(糟糕的)理解是正確的,則需要呼叫它。thunk( async (dispatch))究竟是如何被提供給 dispatch 函式的,以及函式實際上回傳了什么listProducts到dispatch呼叫中HomeScreen()?
uj5u.com熱心網友回復:
Redux 不會呼叫您的listProducts操作創建者,而是在您調度操作時呼叫。thunk redux 中間件檢查 action 值是否是一個物件,即像一個普通的 action 物件,或者一個函式。如果它是一個函式,則中間件呼叫柯里化函式并傳遞dispatch和getState函式,以便處理異步邏輯并可以調度任何進一步的操作。
中間件是如何作業的?
thunk 中間件的實際實作非常短——只有大約 10 行。這是來源,并添加了額外的評論:
Redux thunk 中間件實作,帶注釋
// standard middleware definition, with 3 nested functions: // 1) Accepts `{dispatch, getState}` // 2) Accepts `next` // 3) Accepts `action` const thunkMiddleware = ({ dispatch, getState }) => next => action => { // If the "action" is actually a function instead... if (typeof action === 'function') { // then call the function and pass `dispatch` and `getState` as arguments return action(dispatch, getState) } // Otherwise, it's a normal action - send it onwards return next(action) }換句話說:
- 如果你將一個函式傳遞給 dispatch,thunk 中間件會看到它是一個函式而不是一個動作物件,攔截它,并使用 (dispatch, getState) 作為它的引數呼叫該函式
- 如果它是一個普通的 action 物件(或其他任何東西),它會被轉發到鏈中的下一個中間件
另請參閱 Redux Async 資料流以獲得出色的影片視覺解釋。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/336563.html
標籤:javascript 反应 还原 redux-thunk
上一篇:檢查帶有逗號和句點的字串是否是正確的十進制數Javascript并提取數值
下一篇:如何使用陣列值更新div的背景
