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

gia*_*nni 9 typescript reactjs react-router firebase-authentication react-redux

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

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

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

我的代码供以下参考:

App.js

<PrivateRoute path="/dashboard" component={Dashboard} />
<Route path="/login" component={Login} />
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

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 
      });
    }
  )
 }
}
Run Code Online (Sandbox Code Playgroud)

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;
  }
};
Run Code Online (Sandbox Code Playgroud)

yko*_*ach 7

你应该把它放在你创建 redux store 的地方,应该是你渲染你的 App 组件的地方。您可以在此处查看更多详细信息。如果你经常使用 firebase,我建议你花一些时间来设置这个很棒的库react-redux-firebase