【问题标题】:Where to place firebase.auth().onAuthStateChanged()在哪里放置 firebase.auth().onAuthStateChanged()
【发布时间】:2018-01-02 22:04:05
【问题描述】:

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

现在,我从在用户身份验证中设置的 auth reducer 获取用户的登录状态,但我想在使用 onAuthStateChanged() 刷新页面后保持登录状态。

我应该在哪里放置 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;
  }
};

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 谢谢@ykorach,我通过将函数放在 App.js 中解决了我的问题,但我一定会看看那个库。
    猜你喜欢
    • 2018-05-12
    • 2020-08-06
    • 2016-10-02
    • 2021-06-03
    • 1970-01-01
    • 2019-05-03
    • 2018-08-17
    • 1970-01-01
    • 2019-03-26
    相关资源
    最近更新 更多