Heim > Fragen und Antworten > Hauptteil
P粉0378809052023-08-27 12:25:17
要检查用户是否已登录,您可以使用'onAuthStateChanged'方法。
将此信息存储在组件的状态中,或者使用它来有条件地渲染组件的部分。
import React, { useEffect, useState } from 'react'; import firebase from 'firebase/app'; import 'firebase/auth'; export default function Home() { const [user, setUser] = useState(null); useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { setUser(user); }); return () => unsubscribe(); }, []); return ( <main> <h1>Hello World</h1> {user ? ( <p>authenticated user</p> ) : null} </main> ); }
要在服务器端执行用户身份验证,Next.js提供了'getServerSideProps'来获取用户的身份验证状态
import firebase from 'firebase/app'; import 'firebase/auth'; export default function Home({ user }) { return ( <main> <h1>Hello World</h1> {user ? ( <p>authenticated user</p> ) : null} </main> ); } export async function getServerSideProps(context) { const user = await new Promise((resolve, reject) => { firebase.auth().onAuthStateChanged(user => { resolve(user); }); }); return { props: { user, }, }; }
更新的解决方案:
创建一个服务器端路由
import firebase from 'firebase/app'; import 'firebase/auth'; import express from 'express'; const app = express(); app.get('/api/user', async (req, res) => { const user = await new Promise((resolve, reject) => { firebase.auth().onAuthStateChanged(user => { resolve(user); }); }); res.send(user); }); app.listen(3000, () => { console.log('Server started at http://localhost:3000'); });
客户端代码
import React, { useState, useEffect } from 'react'; import axios from 'axios'; export default function Home() { const [user, setUser] = useState(null); useEffect(() => { const fetchUser = async () => { const res = await axios.get('http://localhost:3000/api/user'); const user = res.data; setUser(user); }; fetchUser(); }, []); return ( <main> <h1>Hello World</h1> {user ? ( <p>authenticated user</p> ) : null} </main> ); }