下面的代码来自Brad Traversy在MERN堆栈上的Udemy课程。我是Redux和Redux Thunk的新手,并试图了解其目的=> dispatch =>
是什么。我知道它来自Redux Thunk,它是在Redux存储文件中设置的。我认为dispatch
在此使用该命令是为了从此函数调度多个动作,并阅读该= ([arg(s)]) => dispatch =>
语法是currying的示例(尽管由于curring每个函数都有一个参数,所以这似乎并不正确)。
我非常感谢您的帮助=> 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.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句