首页 > 解决方案 > Redux Thunk `([arg(s)]) => dispatch =>` 的目的?

问题描述

下面的代码来自 Brad Traversy 在 MERN 堆栈上的 Udemy 课程。我是 Redux 和 Redux Thunk 的新手,我试图了解其目的=> dispatch =>是什么。我知道它来自 Redux Thunk,它是在 Redux 存储文件中设置的。我认为dispatch这里使用它是为了从这个函数调度多个动作,并读到= ([arg(s)]) => dispatch =>语法是柯里化的一个例子(尽管这看起来不正确,因为柯里化每个函数都有一个参数)。

我将不胜感激任何帮助理解=> dispatch =>

(其他小的混淆点:在课程中,该函数setAlert被称为一个动作,但我不确定这是正确的,因为它包含多个动作调度。)

export const setAlert = (msg, alertType, timeout = 5000) => dispatch => {
  const id = uuidv4();
  dispatch({
    type: SET_ALERT,
    payload: { msg, alertType, id }
  });

  setTimeout(() => dispatch({ type: REMOVE_ALERT, payload: id }), timeout);
};

标签: reactjsreduxredux-thunk

解决方案


这里有几件事:

1)setAlert是通常所说的“动作创建者”。它是一个返回动作的函数,您可以稍后分派。

2) Redux-Thunk 允许您将表单的函数(dispatch) => {}用作操作(代替更普通的对象表单{ type, payload }

如果您在查看它们如何组合在一起之前单独查看它们可能会有所帮助:

// This is an action creator (a function that returns an action)
// This doesn't use redux thunk, the action is just a simple object.
// Because it's an action creator you can pass in arguments
// Because it's not a thunk you can't control when then dispatch happens
const setAlertActionCreator = (msg, alertType) => {
  const id = uuidv4();
  return {
    type: SET_ALERT,
    payload: { msg, alertType, id }
  };
};

// You use this as:
dispatch(setAlertActionCreator("msg", "type"));

// This is not an action creator it's just an action.
// This IS a redux-thunk action (it's a (dispatch) => {} function not a simple object)
// Because it's not an action creator you can't pass in arguments to get a custom action back
// Because it IS a redux-thunk action you can dispatch more actions later
const setAlertThunk = (dispatch) => {
  setTimeout(() => dispatch({
    type: SET_ALERT,
    payload: {
      message: "fixed message",
      alertType: "fixed alertType",
      id: "fixed id",
    }
  }), 5000);
};

// You use this as:
dispatch(setAlertThunk);

// When you combine both patterns you gain the ability
// to both pass in arguments and to create additional dispatches
// as the function runs (in this case dispatching again after a timeout.)
// I won't repeat your code, but will show how you would call it:

dispatch(setAlertActionCreator("msg", "type"));

// ie: you use it the same way as example 1.

推荐阅读