Redux中store.dispatch()的参数为函数?

在Redux官方示例shopping-cart中

//src/actions/index.js
const receiveProducts = products => ({
    type: types.RECEIVE_PRODUCTS,
    products: products
})
export const getAllProducts = () => dispatch => {
    shop.getProducts(products => {
        dispatch(receiveProducts(products))
    })
}
//src/index.js
import { getAllProducts } from './actions'
//省略
//console.log(getAllProducts());
//在chrome中打印如下
//function (dispatch) {
//        __WEBPACK_IMPORTED_MODULE_0__api_shop__["a" /* default //*/].getProducts(function (products) {
//            dispatch(receiveProducts(products));
//        });
//    }
//
store.dispatch(getAllProducts())

store.dispatch()的参数应该是action吧,但是这里的getAllProducts()执行结果是一个函数声明。

阅读 14.7k
2 个回答

因为action也可以是一个函数,比如异步action当中用到的redux-thunk这个中间件,本质上就是检测为函数类型的action。

store.dispatch()是 View 发出 Action 的唯一方法。View 要发送多少种消息,就会有多少种 Action。如果都一一手写,会很麻烦。可以定义一个函数来生成 Action,这个函数就叫 Action Creator。上面代码中,getAllProducts函数就是一个 Action Creator。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题