放置firebase.auth()的位置.onAuthStateChanged()

时间:2017-07-27 09:13:53

标签: reactjs typescript react-router firebase-authentication react-redux

我正在使用react和redux实现基本的firebase身份验证。 我根据this link上的react-router示例创建了受保护的路由,到目前为止一切正常。

现在,我从我的auth reducer获取用户身份验证时设置的用户的loggedIn状态,但是我希望在页面刷新后使用onAuthStateChanged()保持loggedIn状态。

我应该在哪里放置onAuthStateChanged()函数?有没有最好的做法来使用它?

我的代码供以下参考:

App.js

<PrivateRoute path="/dashboard" component={Dashboard} />
<Route path="/login" component={Login} />

ProtectedRoute.js

const PrivateRoute = ({ component: Component, ...rest }) => {
const { loggedIn } = rest;
return (
    <Route {...rest} render={props => (
      loggedIn ? (<Component {...props} />) : (
        <Redirect to={{
          pathname: '/login',
          state: { from: props.location }
        }} />
      )
    )} />
  )
}

function mapStateToProps({auth}){
  return {
    loggedIn: auth.loggedIn
  }
}
export default connect(mapStateToProps)(PrivateRoute);

actions_auth.js

export const loginUser = ({ email, password }, callback ) => {
console.log(email, password)
return(dispatch) => {
  dispatch({ type: LOGIN_USER });
  auth.signInWithEmailAndPassword(email, password)
    .then(
      user => { 
        dispatch({
        type: LOGIN_USER_SUCCESS,
      payload: user
    });
    callback();
  },
  error => { 
      console.log( error.message );        
      dispatch({ 
        type: LOGIN_USER_FAIL,
        error: error.message 
      });
    }
  )
 }
}

reducer_auth.js

const INITIAL_STATE = {
  email: '',
  password: '',
  error: '',
  loading: false,
  loggedIn: false
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case EMAIL_CHANGED:
      return { ...state, email: action.payload };
    case PASSWORD_CHANGED:
      return { ...state, password: action.payload };
    case LOGIN_USER:
      return { ...state, loading: true, error: '' };
    case LOGIN_USER_SUCCESS:          
      return { ...state, ...INITIAL_STATE, user: action.payload, loggedIn: true };
    case LOGIN_USER_FAIL:
      return { ...state, error: action.error };
    case LOGOUT_USER:
      return { ...state, ...INITIAL_STATE };
    default:
      return state;
  }
};

1 个答案:

答案 0 :(得分:3)

您应该在创建redux store的位置找到它,应该是您呈现App组件的位置。 您可以查看here了解更多详情。 如果你经常使用firebase,我建议花一些时间来设置这个很棒的库react-redux-firebase