【问题标题】:How redux thunk calls curried async thunk functions?redux thunk 如何调用 curried 异步 thunk 函数?
【发布时间】:2021-12-11 11:40:01
【问题描述】:

如果 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 函数实际返回到 HomeScreen() 内的 dispatch 调用中的内容?

【问题讨论】:

    标签: javascript reactjs redux redux-thunk


    【解决方案1】:

    Redux 不会调用您的 listProducts 操作创建者,而是在您分派操作时调用。 thunk redux 中间件检查动作值是否是一个对象,即像一个普通的动作对象,还是一个函数。如果它是一个函数,则中间件调用 curried 函数并传递 dispatchgetState 函数,以便处理异步逻辑并分派任何进一步的操作。

    How does the middleware work?

    thunk 中间件的实际实现很短——只有 大约10行。这是源代码,另外添加了 cmets:

    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) 作为其参数
    • 如果它是一个普通的动作对象(或其他任何东西),它会被转发到链中的下一个中间件

    See also the Redux Async data flow 以获得精彩的动画视觉解释。

    【讨论】:

    • 所以 thunk 中间件相当于调用listProducts(dispatch, getState)?那不会返回匿名内部异步函数吗?
    • @user3491700 不,中间件调用action值,从listProducts()返回函数,即async (dispatch) => { ....。您在调度它时调用listProducts,即dispatch(listProducts()),并且返回值是您调用它的“内部函数”。因为中间件看到了这个函数,所以它调用它,传递新的参数。
    • 耶,有人真的在阅读和链接我写的新的 thunk 文档页面! :)
    猜你喜欢
    • 2023-03-23
    • 2017-10-23
    • 2018-06-29
    • 2019-11-12
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 2020-10-28
    • 2020-01-17
    相关资源
    最近更新 更多