Javascript 内部函数如何获得';调度';参数
我是一个新的反应Redux 但我有个问题 内部函数(Javascript 内部函数如何获得';调度';参数,javascript,reactjs,react-redux,Javascript,Reactjs,React Redux,我是一个新的反应Redux 但我有个问题 内部函数(async dispatch)如何接收dispatch()参数 GetCurrentUserInfo操作创建者函数: export const getCurrentUserInfo = () => async dispatch => { const response = await axios.get('/api/users/me') dispatch({ type: userActions.SET_CURRENT
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())
中吗?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){
// ...
};
}
export const AuthGuard = connect(
state => ({}),
dispatch => ({
authOrRedirect: () => {
const getUserInfoDispatcher = getCurrentUserInfo(); // create dispatcher
getUserInfoDispatcher(dispatch).catch(() => { // call dispatcher
history.replace('/login')
})
}
})
)(AuthGuardComponent)
dispatchProp可以这样写:
const getCurrentUserInfo = function(){ // create getCurrentUserInfo dispatcher
return async function(dispatch){
// ...
};
}
export const AuthGuard = connect(
state => ({}),
dispatch => ({
authOrRedirect: () => {
const getUserInfoDispatcher = getCurrentUserInfo(); // create dispatcher
getUserInfoDispatcher(dispatch).catch(() => { // call dispatcher
history.replace('/login')
})
}
})
)(AuthGuardComponent)
常见模式
显然,您对这两种模式感到困惑,您可能在某些地方看到了这两种模式:
- 答:
:调用“调度函数”getCurrentUserInfo()(调度)
- B:
:分派“操作”分派(getCurrentUserInfo())
getCurrentUserInfo()
返回一个“分派函数”(不是官方术语),即调用dispatch(someAction)
getCurrentUserInfo()(调度)
调用此“调度函数”
(B)是一种模式,如果
getCurrentUserInfo()
将是一个“操作创建者”(在您的情况下不是这样),也就是说,一个函数返回一个“操作”,比如{type:…,users:…}
,我明白了,谢谢,顺便说一句,它是dispatch(getCurrentUserInfo())
和getCurrentUserInfo()(dispatch)
相同?没有。我更新了答案来解释这两种模式。嗨,我发布的代码来自:https://github.com/huwcarwyn/react-laravel-boilerplate/blob/master/resources/assets/js/components/AuthGuard/AuthGuard.jsx
,它是这样写的默认值:`return dispatch(getCurrentUserInfo()).catch(()=>{history.replace('/login')}`这是印刷错误吗?