当我试图更改数据时-更改正在进入我的FiRestore数据库,这是可以的,但当我重新加载页面或注销并try 再次登录时-用户数据不会出现在我的项目中,但也会存储在我的Firestore Database中.如何在重新加载页面后保存和显示项目中的用户数据?

这是我的代码

    const [email, setEmail] = useState('')
    const [phone, setPhone] = useState('')
    const [language, setLanguage] = useState('')
    const [valute, setValute] = useState('')
    const [instagram, setInstagram] = useState('')
   

    const {user} = UserAuth()


    const createUser = (email, password) => {
        createUserWithEmailAndPassword(auth, email, password)
        .then((userCredential) => {
            const user = userCredential.user;
            const uid = user.uid;
            setDoc(doc(db, 'users', uid), {
                email: email,
                name: name,
                password: password,
                phone: phone,
                language: language,
                instagram: instagram,
                valute: valute,
            });
          })
          .catch((error) => {
            const errorCode = error.code;
            const errorMessage = error.message;
            // ..
          });
    }

    const updatePerson = async(email, phone, language, valute, instagram, name, ) => {
      await updateDoc(doc(db, 'users', user.uid), {email, phone, language, valute, instagram, name})
    }

    <input type="text" placeholder={name || user.displayName || user.email || user.phoneNumber} className='form-control' onChange={(e) => setName(e.target.value)}/>
    <input type="text" placeholder={instagram} className='form-control' onChange={(e) => setInstagram(e.target.value)}/>
    <input type="text" placeholder={email} className='form-control' onChange={(e) => setEmail(e.target.value)}/>
    <input type="text" placeholder={phone} className='form-control' onChange={(e) => setPhone(e.target.value)}/>
    <input type="text" placeholder={language} className='form-control' onChange={(e) => setLanguage(e.target.value)}/>
    <input type="text" placeholder={valute} className='form-control' onChange={(e) => setValute(e.target.value)}/>

推荐答案

我已经在我的问题上找到了答案.

我们期待着onSnapshot会在我们的应用程序加载后立即被神奇地调用-它需要一些时间从我们的集合中获取文档.我将添加指示数据是否仍在加载的附加标志:

function useUserData(userId) {
  const [userData, setUserData] = useState(undefined);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    if (!userId) return; // null or undefined is passed, so just do nothing

    const unsubscribe = onSnapshot(doc(db, "users", userId), (doc) => {
      setIsLoading(false);
      if (doc.exists()) {
        setUserData(doc.data()); // found and setting a user
      } else {
        setUserData(null); // null means user not found in users collection
      }
    });

    return () => unsubscribe();
  }, [userId]);

  return { userData, isLoading };
}

然后像这样使用它:

function Profile() {  /// or props here
 const { isLoading, userData } = useUserData(user.uid); /// if you use props just simple write uid
 if (isLoading) {
  return <span>Loading...</span>;
 }
 if (!userData) {
  return <span>Ooops. Profile not found</span>;
 }
 
 return <span>{userData.firstName}</span>
}

Reactjs相关问答推荐

可选链和useState挂钩

在Reaction常量函数中未更新状态变量

使用Reaction-Hook-Form时未激发React.js onBlur事件

无法在REACTION TANSTACK查询中传递参数

安装使用环境的BIT组件的依赖项

无法使用导入app/page.jsx的组件中的tailwind 类文本操作和自定义动画

onClick 事件处理程序未应用于样式组件

使用获取的数据更新状态,但在try console.log 时它给出未定义

从 redux 调用UPDATE_DATA操作时状态变得未定义

无法通过react 路由中的链接传递信息

从ReactDataGridtry 将数据传递给父组件

当我使用 Firebase Auth 在 React 中刷新主页时显示登录页面

无法读取未定义的属性(读取值)...TypeError:无法读取未定义的属性(读取值)

类型错误:类型typeof import(js-cookie)上不存在属性get

谁能根据经验提供有关 useEffect 挂钩的更多信息

加密 Django Rest Framework API 响应 + 解密响应应用程序中的响应

使用 React、Redux 和 Firebase 的无限循环

React Hooks 表单在日志(log)中显示未定义的用户名

单击按钮时获取react 表中每一行的属性

Cypress 中的 process.env 空对象