useNavigate 重定向但不加载

huangapple go评论66阅读模式
英文:

useNavigate redirecting but not loading

问题

以下是您提供的内容的翻译部分,不包括代码部分:

"the URL shows that it is login page but everything is white, and when I reload it loads the page.
in the console says that many variables from the previous page are null, it seems like it's still on the previous page. why is this happening?
The previous page and the code:"

"URL显示这是登录页面,但一切都是白色,当我刷新时,它才加载页面。
控制台显示前一页的许多变量为空,看起来仍然在前一页。为什么会发生这种情况?
前一页和代码:"

"and when i click logout this happens:"

"当我点击注销时发生以下情况:"

"i consoled log currentUser and currentUser.email before logout, and it's not null, this happens after logging out."

"在注销之前,我通过控制台记录了currentUser和currentUser.email,它们不为空,但在注销后发生了变化。"

请注意,由于您的请求,我只提供了内容的翻译,没有提供代码的翻译。如果您需要有关代码的帮助或解释,请随时提出。

英文:

the URL shows that it is login page but everything is white, and when I reload it loads the page.
in the console says that many variables from the previous page are null, it seems like it's still on the previous page. why is this happening?
The previous page and the code:
useNavigate 重定向但不加载

import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import '../styles/UserProfile.css'
import { useAuth } from '../services/authContext'

export default function UserProfile() {
  const { currentUser, logout } = useAuth()
  const navigate = useNavigate()
  const [errorMessage, setErrorMessage] = useState(null)

  async function handleLogout() {
    try {
      await logout()
      navigate("/login")
    } catch (error) {
      console.log(error)
      setErrorMessage('An error ocurred when trying to logout')
    }
  }

  return (
    <div className="container profile">
      <div className="profile">
        <h1>Profile</h1>
        {errorMessage && (
          <div className="error-container">
            <strong>{errorMessage}</strong>
          </div>
        )}
        <div className="row">
          <h3>Email</h3>
          <p>{currentUser.email}</p>
        </div>
        <div className="row">
          <a>Change email</a>
        </div>
        <div className="row">
          <a>Reset password</a>
        </div>
        <button onClick={handleLogout}>Logout</button>
      </div>
    </div>
  )
}

and when i click logout this happens:
useNavigate 重定向但不加载
useNavigate 重定向但不加载
when i reload it loads normally
useNavigate 重定向但不加载

useAuth code:

import React, { createContext, useContext, useEffect, useState } from 'react'
import {
  createUserWithEmailAndPassword,
  onAuthStateChanged,
  signInWithEmailAndPassword,
  signOut,
} from 'firebase/auth'
import { auth } from '../firebase'

const AuthContext = createContext()

export function useAuth() {
  return useContext(AuthContext)
}

export function AuthProvider({ children }) {
  const [currentUser, setCurrentUser] = useState()

  function signUp(email, password) {
    return createUserWithEmailAndPassword(auth, email, password)
  }

  function login(email, password) {
    return signInWithEmailAndPassword(auth, email, password)
  }

  function logout() {
    return signOut(auth)
  }

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, user => {
      setCurrentUser(user)
    })
    return unsubscribe
  }, [])

  return (
    <AuthContext.Provider
      value={{
        signUp: signUp,
        login: login,
        logout: logout,
        currentUser: currentUser,
      }}
    >
      {children}
    </AuthContext.Provider>
  )
}

login code:

import React, { useState } from 'react'
import { useAuth } from '../services/authContext'
import { useNavigate, Link } from 'react-router-dom'
import Header from '../components/Header'

export default function Login() {
  const { login } = useAuth()
  const navigate = useNavigate()
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [loading, setLoading] = useState(false)
  const [errorMessage, setErrorMessage] = useState(null)

  async function handleSubmit(element) {
    element.preventDefault()

    setLoading(true)

    if (password.length < 6) {
      setErrorMessage('The password need to have at least 6 characters!')
      setLoading(false)
      return
    }

    try {
      await login(email, password)
      navigate('/')
    } catch (error) {
      setErrorMessage('An error occured when trying to login')
    }
    setLoading(false)
  }

  return (
    <div className="container">
      <Header />
      <h2>Login</h2>
      {errorMessage && (
        <div className="error-container">
          <strong>{errorMessage}</strong>
        </div>
      )}
      <form onSubmit={handleSubmit}>
        <label>Email</label>
        <input
          type="email"
          value={email}
          onChange={e => setEmail(e.target.value)}
        />

        <label>Password</label>
        <input
          type="password"
          value={password}
          onChange={e => {
            setPassword(e.target.value)
          }}
        />
        <button disabled={loading} className="button-block" type="submit1">
          Login
        </button>
      </form>

      <div className="center">
        <p>
          ForgotPassword ? <Link to="/forgot-password">Reset password</Link>
        </p>
        <p>
          Don't have an account ? <Link to="/signup">Create account</Link>
        </p>
      </div>
    </div>
  )
}

i consoled log currentUser and currentUser.email before logout, and it's not null, this happens after logging out.

答案1

得分: 1

UserProfile.jsx:32:1<p>{currentUser.email}</p>。据我所知,currentUser 对象在导航动作生效之前至少重渲染了一次,导致 currentUser 被置为 null 后,UserProfile 组件再次渲染。在 currentUser 为 null 时,UserProfile 组件访问 currentUser.email 会导致错误。

你应该在UI上添加一个守卫,只有在 currentUser 非空时才渲染有效内容。

示例:

export default function UserProfile() {
  const { currentUser, logout } = useAuth();
  const navigate = useNavigate();
  const [errorMessage, setErrorMessage] = useState(null);

  async function handleLogout() {
    try {
      await logout();
      navigate("/login");
    } catch (error) {
      console.log(error);
      setErrorMessage('注销时发生错误');
    }
  }

  if (!currentUser) {
    return <div>没有当前用户请登录</div>;
  }

  return (
    <div className="container profile">
      <div className="profile">
        <h1>个人资料</h1>
        {errorMessage && (
          <div className="error-container">
            <strong>{errorMessage}</strong>
          </div>
        )}
        <div className="row">
          <h3>电子邮件</h3>
          <p>{currentUser.email}</p>
        </div>
        <div className="row">
          <a>更改电子邮件</a>
        </div>
        <div className="row">
          <a>重置密码</a>
        </div>
        <button onClick={handleLogout}>注销</button>
      </div>
    </div>
  )
}
英文:

UserProfile.jsx:32:1 is &lt;p&gt;{currentUser.email}&lt;/p&gt;. As far as I can tell it appears the currentUser object is nullified and the UserProfile component is rerendered at least once prior to the navigation action being effected to navigate the user to the &quot;/login&quot; path. The UserProfile component falls over when attempting to access currentUser.email when currentUser is null.

You should place a guard on the UI to only render valid content when currentUser is non-null.

Example:

export default function UserProfile() {
  const { currentUser, logout } = useAuth();
  const navigate = useNavigate();
  const [errorMessage, setErrorMessage] = useState(null);

  async function handleLogout() {
    try {
      await logout();
      navigate(&quot;/login&quot;);
    } catch (error) {
      console.log(error);
      setErrorMessage(&#39;An error ocurred when trying to logout&#39;);
    }
  }

  if (!currentUser) {
    return &lt;div&gt;No Current user. Log in.&lt;/div&gt;;
  }

  return (
    &lt;div className=&quot;container profile&quot;&gt;
      &lt;div className=&quot;profile&quot;&gt;
        &lt;h1&gt;Profile&lt;/h1&gt;
        {errorMessage &amp;&amp; (
          &lt;div className=&quot;error-container&quot;&gt;
            &lt;strong&gt;{errorMessage}&lt;/strong&gt;
          &lt;/div&gt;
        )}
        &lt;div className=&quot;row&quot;&gt;
          &lt;h3&gt;Email&lt;/h3&gt;
          &lt;p&gt;{currentUser.email}&lt;/p&gt;
        &lt;/div&gt;
        &lt;div className=&quot;row&quot;&gt;
          &lt;a&gt;Change email&lt;/a&gt;
        &lt;/div&gt;
        &lt;div className=&quot;row&quot;&gt;
          &lt;a&gt;Reset password&lt;/a&gt;
        &lt;/div&gt;
        &lt;button onClick={handleLogout}&gt;Logout&lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  )
}

huangapple
  • 本文由 发表于 2023年2月19日 00:05:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75494596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定