reactjs - 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);
};
解决方案
这里有几件事:
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.
推荐阅读
- oracle - 将 varchar2 列转换为数字数据类型时出现无效标识符错误
- jenkins - Jenkins v2.277.3:创建扩展解析器类时出错:找不到类
- javascript - “我在 node.js 中连接 mongo db 时出错”
- c# - ASP.NET Core WebAPI:不支持的媒体类型 - HTTP 415
- ios - 我可以在解码器中同时使用 init() 和初始值吗?
- python - 如何使用多个 where 条件更新记录
- python - 使用 json 列表在 python 中保存 csv
- web-scraping - 网页抓取 html 函数参数并导出到 csv
- php - OroCommerce 不会与传入的电子邮件同步
- qt - QCustomPlot如何重新调整X和Y轴范围