【问题标题】:dispatching function/action vs dispatching {type: x}调度函数/动作与调度 {type: x}
【发布时间】:2020-02-18 00:19:23
【问题描述】:

调用时

store.dispatch(...)

我们可以像这样使用它(1):

store.dispatch(dispatch => {
   dispatch(someOtherAction())
});

或者我们可以像这样使用它(2):

store.dispatch({type: constants.X})

第一个问题:调用 dispatch 的两种不同类型的参数是什么? 第二个问题:调用(1)和调用(2)有什么区别?

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    在 (1) 中,您正在发送一个“thunk”。在 (2) 中,您正在发送一个“动作”。此外,在 (1) 中,someOtherAction 是“动作创建者”。您需要某种额外的中间件(例如,redux-thunk)来调度 thunk。

    通常,您的目标是调度动作,但如果您需要异步调度动作(例如,在 API 调用之后),您可以使用 thunk 来异步调度动作。例如:

    store.dispatch(dispatch => {
      fetch('api/user')
        .then(res => res.json())
        .then(user => {
          dispatch(loadUser(user))
        })
    });
    

    在本例中,我们利用 thunk 概念,仅在从某些 API 加载用户后调度用户加载操作。

    【讨论】:

    • 对,但是如果你这样做dispatch({type: x}),它会直接进入 redux reducer,然后更改根状态并调用 mapStateToProps?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 2020-04-26
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    相关资源
    最近更新 更多