Nat*_*lie 3 reactjs redux redux-thunk
下面的代码来自 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);
};
Run Code Online (Sandbox Code Playgroud)
这里发生了一些事情:
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"));
Run Code Online (Sandbox Code Playgroud)
// 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"));
Run Code Online (Sandbox Code Playgroud)
// 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);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
297 次 |
最近记录: |