Redux等待异步thunk继续前进

问题描述 投票:1回答:1

我目前正在使用redux / redux-thunk来获取使用api-sauce的用户

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.logs不按顺序排列

`dispatching auth token`
`here goes request`
`show login screen`

为什么会这样?

redux react-redux axios redux-thunk
1个回答
2
投票

这是因为对store.dispatch(fetchUser(authToken))的实际调用是同步的 - dispatch()方法is not asynchronous,因此在执行fetchUser()方法之后立即发生日志记录“show login screen”。

如果您希望在从网络请求返回响应后执行loggedInView()(即调用异步方法api.get()),那么您可以考虑以下列方式重构代码:

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'
    })
}

希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.