我是新来反应的,我遇到了这个问题。import React from "react";import firebase from "firebase";import fire from "./firebase"import { Route, BrowserRouter as Router, Switch, Redirect, useHistory, NavLink } from 'react-router-dom';import Header from "./header"import Nav from "./nav"import data from "./data"function Home(){ let userID; let userName; let logg; const history = useHistory(); firebase.auth().onAuthStateChanged((user)=>{ if(user){ userID = user.uid }else{ history.push("/login") } }) return( <> <Header /> <Nav /> <div id = "home" className ="main"> <div class = "headingCont"> <h1>This is home</h1> <NavLink to = {"users/"+userID}><p>Your Profile</p></NavLink> </div> </div> </> ) }export default Home我正在从 firebase 获取用户 id,但它会快速渲染 jsx,因此 userID 的值仍然未定义。因此,当我单击“您的个人资料”时,它会转到 user/undefined 而不是 user/“用户 ID”,我该如何修复它?
1 回答
慕哥9229398
TA贡献1877条经验 获得超6个赞
您应该使用状态而userId不是范围变量。
const [userID, setUserID] = useState(null)
firebase.auth().onAuthStateChanged((user) => {
if (user) {
setUserID(user.uid)
} else {
history.push('/login');
}
});
添加回答
举报
0/150
提交
取消