简体   繁体   English

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

[英]why useRef() hook is setting to null after firebase.auth().createUserWithEmailAndPassword() call?

useRef() is used like: useRef()的用法如下:

const firstname = useRef('');

const lastname = useRef('');

const email = useRef('');

const passwordOne = useRef('');

When I am writing it like this:当我这样写时:

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);
}

I am getting an error that cannot read property value of null .我收到一个错误, cannot read property value of null

But this is working:但这是有效的:

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);
}

How?如何? And why?为什么?

one important thing you have to keep in mind is that you're dealing with asynchronous code, the time in which the statements with await will try to access the ref properties is not guaranteed and the refs might not be initialized yet.您必须记住的一件重要事情是您正在处理异步代码,不能保证带有await的语句尝试访问 ref 属性的时间,并且 refs 可能尚未初始化。

My advice will be to refactor your code to use a Controlled Component with useState instead of handing DOM refs with useRef我的建议是重构您的代码以使用带有useState受控组件,而不是使用useRef处理 DOM 引用

In HTML, form elements such as <input>, <textarea>, and <select> typically maintain their own state and update it based on user input.在 HTML 中,<input>、<textarea> 和 <select> 等表单元素通常会维护自己的 state 并根据用户输入对其进行更新。 In React, mutable state is typically kept in the state property of components, and only updated with setState().在 React 中,可变的 state 通常保存在组件的 state 属性中,并且仅使用 setState() 进行更新。 We can combine the two by making the React state be the “single source of truth”.我们可以通过使 React state 成为“单一事实来源”来将两者结合起来。 Then the React component that renders a form also controls what happens in that form on subsequent user input.然后,呈现表单的 React 组件还控制后续用户输入在该表单中发生的情况。 An input form element whose value is controlled by React in this way is called a “controlled component”.以这种方式由 React 控制其值的输入表单元素称为“受控组件”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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