【问题标题】:Redux Action Creator and Dispatch confusion with syntaxRedux Action Creator 和 Dispatch 与语法混淆
【发布时间】:2021-11-05 13:45:46
【问题描述】:

我在理解这个 productListCreator 语法时遇到了一些问题。使用 thunk,我正在遵循的教程说 thunk 允许我们在函数中编写异步函数。

productListCreator 是一个以 dispatch 作为参数返回异步函数的函数。

但是当你使用调用/将它与 dispatch(productListCreator()) 一起使用时,我很困惑。

productListCreator 没有传递分派参数。相反,它被传递到 useDispatch 钩子中。

所以对我来说,代码是 useDispatch(),它接受 productListCreator 函数并运行它,它没有为“dispatch”传递任何参数。

import axios from 'axios'

const productListCreator = () => 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_ERROR',
            payload: error.message
        })
    }
}


export default productListCreator
const dispatch = useDispatch()
    
    // Retrieve all products at reload
    useEffect(()=>{
        dispatch(productListCreator())
    },[])

【问题讨论】:

    标签: reactjs redux react-redux redux-thunk


    【解决方案1】:

    productListCreator 是“thunk 动作创建者”。它定义了“thunk 函数”,并返回它。那个“thunk 函数”是传递给调度的。然后 thunk 中间件拦截 thunk 函数,调用它,并将(dispatch, getState) 作为参数传入。

    我建议阅读新的 "Writing Logic with Thunks" docs page,它解释了 thunk 的工作原理。

    【讨论】:

      猜你喜欢
      • 2016-12-10
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 2017-03-13
      • 2019-08-24
      • 1970-01-01
      • 2018-09-03
      • 2021-11-01
      相关资源
      最近更新 更多