我對 React JS 很陌生,正在嘗試制作一個應用程式。但是,每當在教科書中輸入內容時,整個應用程式似乎都會凍結然后停止作業。
import React, { useState } from 'react'
import { auth } from './firebase';
import styles from '../static/SignIn.module.css';
import { Link, useNavigate } from "react-router-dom";
import {
// createUserWithEmailAndPassword,
signInWithEmailAndPassword,
onAuthStateChanged,
// signOut,
} from "firebase/auth";
export default function SignIn(){
const [user, setUser] = useState({});
const history = useNavigate();
onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser);
});
// const goBack = () => {
// history.push('/')
// };
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const signIn = async() => {
try {
const user = await signInWithEmailAndPassword(
auth,
email,
password
);
history.push('/home')
console.log(user);
} catch (error) {
console.log(error)
if (password.length < 6){
alert('Password should be at least 6 characters!')
}
}
}
return(
<div className={styles.main}>
<div className={styles.center}>
<h1>Login</h1>
<div className={styles.form}>
<div className={styles.txt_field}>
<input type="text" id='text' name='text' value={email} onChange={e => setEmail(e.currentTarget.value)} required/>
<span></span>
<label>Email ID</label>
</div>
<div className={styles.txt_field}>
<input type="password" id='password' name='password' value={password} onChange={e => setPassword(e.currentTarget.value)} required/>
<span></span>
<label>Password</label>
</div>
<input type="submit" value="Login" onClick={signIn}/>
<div className={styles.signup_link}>
Not a member? <Link to="/signup">Signup</Link>
</div>
</div>
</div>
</div>
)
}
任何幫助將不勝感激,因為這阻止了我進一步進步,因為我需要重新運行應用程式npm start才能使其作業。
uj5u.com熱心網友回復:
我認為您的問題是在SignIn您呼叫onAuthStateChanged偵聽器的組件的每次渲染中。我從未使用過它,但我的猜測是它只需要在組件安裝時呼叫一次。
所以你可以這樣做:
export default function SignIn(){
const [user, setUser] = useState({});
const history = useNavigate();
React.useEffect(() => {
onAuthStateChanged(auth, (currentUser) => setUser(currentUser))
// Notice the empty dependency array, there to make sure the effect is only run once when the component mounts
}, [])
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
// ...
}
uj5u.com熱心網友回復:
我認為一切都很好,因為我嘗試在沒有 firebase 函式的情況下運行您的代碼,只洗掉樣式,只渲染輸入按鈕,它作業正常,并且事件發生完美用于設定電子郵件和密碼欄位。但我認為你應該對你的代碼做一點修改。在推送回家路線之前,請先檢查用戶物件是否包含任何資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/477008.html
標籤:javascript html css 反应
