我是react/firebase的新手,最近我一直在做一个项目,涉及一个用户登录网站,以访问导航栏的不同方面,但是出于某种原因,每次用户登录时,都会短暂地显示正确的导航栏并登录,但不久之后,他们就会注销并发送回登录页面。调试代码时,我发现由于某种原因,一旦用户单击登录按钮,handleSignout函数就会与handleform提交函数一起运行。
附件是我的导航栏和注销功能,因为其中有注销按钮。当我从“注销”按钮中删除onClick={handleSignout()}时,用户不会立即注销,但它无法实现拥有该按钮的目的。
import {
Nav,
NavLink,
Bars,
NavMenu,
NavBtnLink,
} from './Navbar';
import { auth, fdb } from '../../firebase';
import { signOut } from 'firebase/auth';
import { updateDoc, doc } from 'firebase/firestore';
import { useContext } from 'react';
import { AuthContext } from '../../context/auth';
import { useNavigate } from 'react-router-dom';
const Navbar = () => {
const Navigate = useNavigate();
const {user} = useContext(AuthContext);
const handleSignout = async() => {
await updateDoc(doc(fdb,'users', auth.currentUser.uid), {
isOnline: false,
});
await signOut(auth);
Navigate('/Login')
};
return(
<Nav>
<NavLink to='/'>
<h1>logo</h1>
</NavLink>
{user ? (
<>
<Bars />
<NavMenu>
<NavLink to= '/Listings'>
Listings
</NavLink>
<NavLink to= '/Post'>
Post
</NavLink>
<NavLink to= '/contact'>
Contact
</NavLink>
<NavLink to= '/profile'>
Profile
</NavLink>
<NavBtnLink to='/' onClick={handleSignout()}>
Log Out
</NavBtnLink>
</NavMenu>
</>
) : (
<>
<NavMenu>
<NavBtnLink to='/Login'>
Log In / Register
</NavBtnLink>
</NavMenu>
</>
)}
</Nav>
)
};
export default Navbar;
这是我的登录名。js
import React from 'react'
import { useRef, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { auth, fdb } from '../firebase'
import { signInWithEmailAndPassword } from 'firebase/auth'
import { updateDoc, doc } from 'firebase/firestore'
const Login = () => {
const emailRef = useRef();
const errRef = useRef();
const [email, setEmail] = useState('');
const [pwd, setPwd] = useState('');
const [errMsg, setErrMsg] = useState('');
const Navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
try {
const userinfo = await signInWithEmailAndPassword(auth,email,pwd);
await updateDoc(doc(fdb, 'users', userinfo.user.uid),{
isOnline: true,
})
Navigate('/')
} catch (e) {
alert(e)
}
}
return (
<div>
<div className="loginBody">
<p ref = {errRef} className= {errMsg ? "errmsg" : "offscreen"} aria-live="assertive">{errMsg}</p>
<h1 className='loginHeader'>Login</h1>
<form onSubmit={handleSubmit}>
<div className="email">
<label htmlFor="email" id='userLabel'>Email</label>
<br/>
<input
type="text"
id="email"
ref = {emailRef}
autoComplete = "off"
onChange = {((e)=> setEmail(e.target.value))}
value={email}
required
/>
</div>
<div className="pwd">
<label htmlFor="password">Password</label>
<br/>
<input
type="password"
id="password"
autoComplete = "off"
onChange = {((e)=> setPwd(e.target.value))}
value={pwd}
required
/>
</div>
<button id='signIn'>Sign In</button>
</form>
<p className='needAcc'>
Need an Account? <br/>
<span className="line">
<Link to="/Register" id='signUpLink'>Sign Up</Link>
</span>
</p>
</div>
</div>
)
}
export default Login