Firebase onAuthStateChanged未在React App中按预期运行

时间:2016-06-12 04:50:43

标签: reactjs firebase redux firebase-authentication

所以我正在使用firebase构建一个React + redux应用程序。我使用react-router onEnter回调函数(checkAuth)进行路由保护。

export default function getRoutes (checkAuth) {
  return (
      <Router history={browserHistory}>
        <Route path='/' component={MainContainer}>
          <IndexRoute component = {HomeContainer} onEnter = {checkAuth}/>
          <Route path='auth' component = {AuthenticateContainer} onEnter = {checkAuth} />
          <Route path='feed' component = {FeedContainer} onEnter = {checkAuth} />
          <Route path='logout' component = {LogoutContainer} />
        </Route>
      </Router>
  )
}

checkAuth函数调用checkIfAuthed函数以查看是否有currentUser。

function checkAuth (nextState, replace) {
  const isAuthed = checkIfAuthed(store)
  console.log('isAuthed from checkAuth method', isAuthed)
  const nextPathName = nextState.location.pathname
  console.log('nextPathName', nextPathName)
  // debugger
  if (nextPathName === '/' || nextPathName === 'auth') {
    if (isAuthed === true) {
      // debugger
      replace('feed')
    }
  } else {
    // debugger
    if (isAuthed !== true) {
      // debugger
      replace('auth')
    }
  }
}

ReactDOM.render(
  <Provider store = {store}>
    {getRoutes(checkAuth)}
  </Provider>,
  document.getElementById('app')
)

checkIfAuthed函数如下所示:

export function checkIfAuthed (store) {
  // debugger
  // const user = firebase.auth().currentUser
  firebase.auth().onAuthStateChanged((user) => {
    console.log('isAuthed from on state changed', user)
    // debugger
    if (user === null) {
      // debugger
      return false
    } else if (store.getState().isAuthed === false) {
      // debugger
      const userInfo = formatUserInfo(user.displayName, user.photoURL, user.uid)
      // debugger
      store.dispatch(authUser(user.uid))
      // debugger
      store.dispatch(fetchingUserSuccess(user.uid, userInfo))
      // debugger
      return true
    }
    // debugger
    return true
  })
}

但是,const isAuthed 在运行时始终未在checkAuth()函数中定义。导致替换(&#34; feed&#34;)从不运行。我原以为它是虚假或真实的。

此外,如果我在checkIfAuthed函数中使用const user = firebase.auth()。currentUser,则会运行Replace函数,但这需要用户点击登录按钮,而上面的firebase观察者会自动运行。

1 个答案:

答案 0 :(得分:0)

您可以在此处查看此实施

当我们读取用户身份验证并将值设置为Redux https://github.com/x-team/unleash/blob/develop/app/services/authService.js

时的服务

将用户状态设置为redux状态对象https://github.com/x-team/unleash/blob/develop/app/reducers/userReducer.js

时的reducer

动作创建者https://github.com/x-team/unleash/blob/develop/app/actions/UserActions.js

登录状态检查 https://github.com/x-team/unleash/blob/develop/app/components/UnleashApp.jsx#L17

最重要的部分是authService,让我知道任何问题