![](/img/trans.png)
[英]How does firebase.auth().createUserWithEmailAndPassword() works?
[英]why useRef() hook is setting to null after firebase.auth().createUserWithEmailAndPassword() call?
useRef()
的用法如下:
const firstname = useRef('');
const lastname = useRef('');
const email = useRef('');
const passwordOne = useRef('');
當我這樣寫時:
try {
const authUser = await Firebase.auth
.createUserWithEmailAndPassword(
email.current.value,
passwordOne.current.value
);
await Firebase.firestore.doc(`users/${authUser.user.uid}`).set({
firstname: firstname.current.value,
lastname: lastname.current.value,
email: email.current.value
});
history.push(ROUTES.SIGN_IN);
}
catch (error) {
setError(error.message);
}
我收到一個錯誤, cannot read property value of null
。
但這是有效的:
try {
const user = {
firstname: firstname.current.value,
lastname: lastname.current.value,
email: email.current.value
};
const authUser = await Firebase.auth
.createUserWithEmailAndPassword(
email.current.value,
passwordOne.current.value
);
await Firebase.firestore.doc(`users/${authUser.user.uid}`).set(user);
history.push(ROUTES.SIGN_IN);
}
catch (error) {
setError(error.message);
}
如何? 為什么?
您必須記住的一件重要事情是您正在處理異步代碼,不能保證帶有await
的語句嘗試訪問 ref 屬性的時間,並且 refs 可能尚未初始化。
我的建議是重構您的代碼以使用帶有useState
的受控組件,而不是使用useRef
處理 DOM 引用
在 HTML 中,<input>、<textarea> 和 <select> 等表單元素通常會維護自己的 state 並根據用戶輸入對其進行更新。 在 React 中,可變的 state 通常保存在組件的 state 屬性中,並且僅使用 setState() 進行更新。 我們可以通過使 React state 成為“單一事實來源”來將兩者結合起來。 然后,呈現表單的 React 組件還控制后續用戶輸入在該表單中發生的情況。 以這種方式由 React 控制其值的輸入表單元素稱為“受控組件”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.