Redux等待异步thunk继续运行
我目前正在使用redux/redux-thunk来获取一个使用api酱的用户,就像这样Redux等待异步thunk继续运行,redux,react-redux,axios,redux-thunk,Redux,React Redux,Axios,Redux Thunk,我目前正在使用redux/redux-thunk来获取一个使用api酱的用户,就像这样 let authToken = await AsyncStorage.getItem('@TSQ:auth_token') if (authToken) { store.dispatch(fetchUser(authToken)) console.log('show login screen') // dont worry, if the token is invalid, just send
let authToken = await AsyncStorage.getItem('@TSQ:auth_token')
if (authToken) {
store.dispatch(fetchUser(authToken))
console.log('show login screen')
// dont worry, if the token is invalid, just send us to onboarding (api determines this)
loggedInView()
} else {
Onboarding ()
}
....
export const fetchUser = authToken => async dispatch => {
console.log('dispatching auth token')
console.log('here goes request')
let res = await api.get(`/auth/${authToken}`);
if (res.ok) {
console.log('have the user')
dispatch(
setUser(res.data)
)
} else {
dispatch({
type: 'SET_USER_DEFAULT'
})
}
}
运行此代码时,用户仍在加载,并且console.log不正常
`dispatching auth token`
`here goes request`
`show login screen`
为什么会发生这种情况?这是因为对
store.dispatch(fetchUser(authToken))
的实际调用是同步的,即dispatch()
方法,因此在执行fetchUser()
方法后,将立即出现日志记录“显示登录屏幕”
如果您想在您的网络请求返回响应(即调用AsiNC方法<代码> API)时,执行<代码> LoGeDeNeVIEW(/CODE>)>代码>,那么您可以考虑以下方式重构代码:
if (authToken) {
store.dispatch(fetchUser(authToken))
// Remove navigation from here
} else {
Onboarding ()
}
然后:
export const fetchUser = authToken => async dispatch => {
console.log('dispatching auth token')
console.log('here goes request')
let res = await api.get(`/auth/${authToken}`);
if (res.ok) {
console.log('have the user')
// Occurs after network request is complete
console.log('show login screen')
// Add navigation here to go to logged in view now that request is complete
loggedInView()
dispatch(
setUser(res.data)
)
} else {
dispatch({
type: 'SET_USER_DEFAULT'
})
}
希望这有帮助