繁体   English   中英

为什么在 firebase.auth().createUserWithEmailAndPassword() 调用之后 useRef() 挂钩设置为 null?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM