繁体   English   中英

如何通过查看Firebase中的User数据来设置useState

[英]How to set useState by checking User data in Firebase

在查询 Firebase 后,我似乎无法弄清楚如何设置 useState。除了管理员之外,我需要 BOX 等于每个人的“公共 URL”。

import { auth } from "../firebase";
...
  const [BOX, setBox] = useState('');
  useEffect(() => {
if (auth.currentUser?.email === "admin@yahoo.com") {
  setBox("https://admin/link");
   } else {
     setBox("https://public/link");
   }
 },[auth]);

错误总是不同的。 有时它会返回“...空链接”,有时会返回“.network 请求失败”。有时它会显示正确的数据,但当我刷新屏幕时它会遇到其中一个错误。

这是我的 firebase 文件

// Import the functions you need from the SDKs you need
import * as firebase from "firebase";
import 'firebase/firestore';
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
const firebaseConfig = {
...
};

// Initialize Firebase

let app;
if (firebase.apps.length === 0) {
    app = firebase.initializeApp(firebaseConfig);
} else {
    app = firebase.app()
}

const auth = firebase.auth();
const dbFirebase = app.firestore();

export {auth, dbFirebase};

你不能在 if 语句中使用钩子......

 const [box, setBox] = useState('');
  
useEffect(() => {
    if (auth.currentUser?.email === "admin@yahoo.com") {
      setBox("https://admin/link");
       } else {
         setBox("https://public/link");
       }
 },[auth]);
  

对于 firebase 9 你需要像下面这样配置它:

import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'

const firebaseConfig = {...}

initializeApp(firebaseConfig)

export const auth = getAuth()

暂无
暂无

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

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