我是新来的React-Redux!
但我有个问题。
内部函数(async dispatch)如何接收dispatch()参数?
GetCurrentUserInfo操作创建器功能:
export const getCurrentUserInfo = () => async dispatch => {
const response = await axios.get('/api/users/me')
dispatch({
type: userActions.SET_CURRENT_USER_INFO,
users: response.data.data
})
return response.data.data
}getCurrentUserInfo的调用方式:
export const AuthGuard = connect(
state => ({
currentUserSlug: state.session.currentUser
}),
dispatch => ({
authOrRedirect: () => {
return dispatch(getCurrentUserInfo()).catch(() => {
history.replace('/login')
})
}
})
)(AuthGuardComponent)getCurrentUserInfo()不接收任何参数,但这是因为它被封装在dispatch(getCurrentUserInfo())中吗
发布于 2020-12-23 02:53:38
getCurrentUserInfo()返回一个需要一个参数dispatch的函数。您需要调用返回的函数并将dispatch参数传递给它:
export const AuthGuard = connect(
state => ({}),
dispatch => ({
authOrRedirect: () => {
return getCurrentUserInfo()(dispatch).catch(() => {
history.replace('/login')
})
}
})
)(AuthGuardComponent)例如:
显然,您可以像这样编写getCurrentUserInfo():
const getCurrentUserInfo = function(){ // create getCurrentUserInfo dispatcher
return async function(dispatch){
// ...
};
}dispatchProp可以写成这样:
export const AuthGuard = connect(
state => ({}),
dispatch => ({
authOrRedirect: () => {
const getUserInfoDispatcher = getCurrentUserInfo(); // create dispatcher
getUserInfoDispatcher(dispatch).catch(() => { // call dispatcher
history.replace('/login')
})
}
})
)(AuthGuardComponent)常见模式
显然,您对这两种模式感到困惑,这两种模式您可能在某处见过:
getCurrentUserInfo()(dispatch):call a "dispatching function"dispatch(getCurrentUserInfo()):dispatch an "action"(A)适用于您的情况,因为getCurrentUserInfo()返回一个"dispatching function“(非正式术语),即调用dispatch( someAction )的函数。
getCurrentUserInfo()(dispatch)调用这个“调度函数”。
(B)是一种模式,如果getCurrentUserInfo()是“操作创建者”(在您的例子中不是),也就是返回“操作”的函数,如{ type: ..., users: ... },则会使用该模式。
https://stackoverflow.com/questions/65411634
复制相似问题