为什么刷新时将用户重定向到登录页面? [英] Why does the user getting redirected to the login page on refresh?

查看:47
本文介绍了为什么刷新时将用户重定向到登录页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,有一个简单的REACTJS应用,其中使用了Firebase.

Okay, there's this simple REACTJS app, where firebase is used.

登录后,除了单击刷新图标外,其他所有功能均正常运行.完成此操作后,它会将您重定向到要求您登录的上一个地方.这就是这个新生的编码器要解决的问题!

There once you login everything works fine except when you hit the refresh icon. The moment you do it, it redirects you to the previous place where you were asked to login. That's the problem that this newly-born coder is trying to solve!

我可以为您提供以下代码段:

I can give you following snippets of code:

  1. 这是着陆页

function Landing() {

    const [{ }, dispatch] = useStateValue();

    firebase.auth().setPersistence(firebase.auth.Auth.Persistence.NONE)
        // .then(function () {
        //     console.log("successfully set the persistence");

        //     return firebase.auth().signInWithPopup(provider);

        // })
        .catch(function (error) {
            console.log("failed to ser persistence: " + error.message)
        });


    firebase.auth().onAuthStateChanged((user) => {
        if (user) {
            console.log('user is logged in');

        } else {
            console.log('user is logged out now')

        }
    });
    const signIn = () => {
        auth
            .signInWithPopup(provider)
            .then((result) => {
                dispatch({
                    type: actionTypes.SET_USER,
                    user: result.user

                })
            }).catch((error) => alert(error.message))
    }

  1. reducer.js代码段

export const initialState = {
    user: null,
}

export const actionTypes = {
    SET_USER: 'SET_USER',
    LOGOUT_USER: 'LOGOUT_USER'
}

const reducer = (state, action) => {
    console.log(action)
    switch (action.type) {
        case actionTypes.SET_USER:
            return {
                ...state,
                user: action.user,
            }


        case actionTypes.LOGOUT_USER:
            return {
                ...state,
                user: null,
            }

        default:
            return state;

  1. 这是firebase.js的

是的,这里使用的是Google身份验证

Yes, Google Authentication is what's being used here

import firebase from 'firebase';



// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
    //config
};

// const user = firebase.auth().currentUser;
// console.log(user);

const firebaseApp = firebase.initializeApp(firebaseConfig)

const db = firebaseApp.firestore();
const storage = firebase.storage();
const auth = firebaseApp.auth();
const provider = new firebase.auth.GoogleAuthProvider();





export default db;
export { auth, provider, storage }

  1. 最后是app.js的

function App() {

  const [{ user }, dispatch] = useStateValue();

  console.log(user);
  
  return (
    <div className="app">


      {!user ? (
        <Landing />
      ) : (
        <App />
)


</div>

非常感谢您对此事的关注!

Your attention to this matter is greatly appreciated!

哦,下面的问题也与此有关.它可以帮助您更好地了解此问题.因此,请务必同时查看!

Oh by the way this following question is also related to this. It might help you to get a better idea of this issue. So make sure to take a look at that as well!

如何保持已登录用户的身份用firebase?

再次感谢!

推荐答案

示例代码.工作


import firebase from 'firebase/app';
import 'firebase/auth';
import { useEffect, useState } from 'react';

import firebaseConfig from './firebase-config';

const firebaseApp = firebase.initializeApp(firebaseConfig);
const googleProvider = new firebase.auth.GoogleAuthProvider();

firebaseApp.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
  .then(function () {
    // return firebaseApp.auth().signInWithPopup(googleProvider)
  })
  .catch(function (error) {
    console.log(error)
  });
function App() {
  const [user, setUser] = useState(null)

  useEffect(() => {
    firebaseApp.auth().onAuthStateChanged((res) => {
      console.log("onAuthStateChanged", res)
      if (res) {
        setUser(res)
        // console.log('user is logged in', user);
      } else {
        setUser(null)
        // console.log('user is logged out now')

      }
    });
  }, [])

  const signInWithGoogle = (e) => {
    firebaseApp.auth()
      .signInWithPopup(googleProvider)
      .then((result) => {
        // console.log(result)
        // setUser(result.additionalUserInfo)
      }).catch(err => {
        // console.log(err)
      })
  }
  const signOut = (e) => {
    firebaseApp.auth().signOut()
  }
  return (
    <div>
      <h1>Firebase Authentication</h1>
      {
        user
          ? (
            <div>
              <p>Hello, {user.displayName}</p>
              <button onClick={signOut}>Sign out</button>
            </div>
          )
          : (
            <div>
              <p>Please sign in.</p>
              <button onClick={signInWithGoogle}>Sign in with Google</button>
            </div>
          )
      }

    </div>
  );
}

export default App;

这篇关于为什么刷新时将用户重定向到登录页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆