如何检查用户是否已登录,使用Firebase进行本机响应?

K.W*_*.Wu 2 react-native redux react-redux

到目前为止,这就是我使用redux全局维护登录状态的原因。在我的登录屏幕中,我正在使用动作创建者来登录用户,就像这样...

    // In LoginScreen file
    onLogin = () => {
      this.props.accountLogin({ email, password });
    }
Run Code Online (Sandbox Code Playgroud)

并在动作文件accountLogin中定义为:

    // In auth_action file
    export const accountLogin = ({ email, password }) => {
      firebase.auth().signInWithEmailAndPassword(email, password)
        .then(user => {
          dispatch({ type: LOGIN_SUCCESS, payload: user })});
      });
    };
Run Code Online (Sandbox Code Playgroud)

然后,在reduce文件中,大小写LOGIN_SUCCESS是这样处理的...

    // In auth_reducer file
    const INITIAL_STATE = {
      // ... Other stuff
      user: null
    };
    export default function (state = INITIAL_STATE, action) {
      // ... Other cases
      // Login Successful case
      case LOGIN_SUCCESS:
        return { ...state, user: action.payload };
        // After this return statement, I now have user's profile info
    };
Run Code Online (Sandbox Code Playgroud)

因此,我的问题是,如何保存用户的个人资料信息,以便下次用户打开该应用程序时,他们不必重新登录?我已经做了一些研究,这就是我所拥有的:

    // Use autoRehydrate and persistStore in 'redux-persist'
    // In store file
    import { createStore, compose, applyMiddleware } from 'redux';
    import thunk from 'redux-thunk';
    import { autoRehydrate, persistStore } from 'redux-persist';
    import { AsyncStorage } from 'react-native';
    import reducers from '../reducers';

    const store = createStore(
      reducers,
      {},
      compose(
        applyMiddleware(thunk),
        autoRehydrate()
      )
    );

    persistStore(store, { storage: AsyncStorage, whitelist: ['auth'] });

    export default store;
Run Code Online (Sandbox Code Playgroud)

当然,我确实处理REHYDRATEauth_reducer文件中的大小写。但是,确实如此,在用户重新打开应用程序之后,我获得了该用户上次使用该应用程序的上一次的用户信息,如何使用这些信息来继续修改Firebase数据库中的数据?

例如,如果用户重新打开应用程序并希望更改其名称,firebase怎么知道这是授权用户?如何编写此changeName功能?

sou*_*tot 6

这种方法可以帮助您。在您的componentWillMount中设置

firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        console.log('user logged')
      }
   });
Run Code Online (Sandbox Code Playgroud)

此处提供更多信息:https : //firebase.google.com/docs/auth/

  • 是的。在记录时,用户名将始终在 firebase 数据中可供您使用。以下是有关它的更多信息:https://firebase.google.com/docs/auth/web/manage-users 但是,有时您需要存储更多信息,那么我建议您将用户放在您的数据库中并获取那里的数据。管理存储中的数据比身份验证更容易。 (2认同)