Redux Thunk `([arg(s)]) => dispatch =>` 的目的?

Purpose of 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);
};

语法 () => dispatch => 等同于:

function response(){
    return function (dispatch){
       //Some code here
    }
}

所以,基本上你可以说的是,它是一种编写相同函数的现代方式。 => dispatch => 正在返回一个将在调用 action 时执行的函数。

希望这会有所帮助。

=> dispatch => 

只不过是函数返回另一个函数的语法糖。因为胖箭头函数 => 被用来代替普通函数。

喜欢

function abc(a,b){
return a+b;
} 

等同于const abc = (a,b) => a+b ;

因此您不必编写 return 关键字。

所以在你的情况下它是相同的 => dispatch => 和下面的那个,它返回一个匿名函数与 。 dispatch 作为论据

function response(){
    return (dispatch){
       //some code here
    }
}

希望对你有帮助,有疑问欢迎留言

这里发生了几件事:

1) setAlert就是通常所说的"action creator"。这是一个 returns 您可以稍后分派的操作的功能。

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.