如何验证登录并有条件地呈现(ReactJS 和 Firebase)?
How to verify login and render conditionally (ReactJS and Firebase)?
我想确保用户在 运行 呈现 A 或 B 之前已登录。
当我 console.log 它时,当我检查我是否登录时,我在 return 中得到一个 true,但是呈现了错误的 if 语句。
我认为这是因为 firebase 需要时间来加载,而我的函数在 firebase 完成之前呈现。
const renderForm = () => {
let isLoggedin = false;
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
isLoggedin = true;
console.log(isLoggedin + " Logged in")
} else {
isLoggedin = false;
}
});
return (
<div>
{isLoggedin ? (<AddNewCountryForm />) : (<p>You have to log in</p>)}
</div>
)
}
有人可以解释我应该如何继续解决这个问题吗?显然,如果用户已登录,我想呈现组件。
谢谢,
您需要将 isLoggedIn
转换为 React 状态而不是局部变量。
按照下面的代码,当 isLoggedIn
是 false
时,您应该看到 <p>You have to log in</p>
否则 AddNewCountryForm
组件应该呈现。
const renderForm = () => {
const [isLoggedin, setIsLoggedIn] = React.useState(false);
firebase.auth().onAuthStateChanged(function(user) {
setIsLoggedIn(!!user);
});
return (
<div>
{isLoggedin ? (<AddNewCountryForm />) : (<p>You have to log in</p>)}
</div>
)
}
希望对您有所帮助。
我想确保用户在 运行 呈现 A 或 B 之前已登录。
当我 console.log 它时,当我检查我是否登录时,我在 return 中得到一个 true,但是呈现了错误的 if 语句。
我认为这是因为 firebase 需要时间来加载,而我的函数在 firebase 完成之前呈现。
const renderForm = () => {
let isLoggedin = false;
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
isLoggedin = true;
console.log(isLoggedin + " Logged in")
} else {
isLoggedin = false;
}
});
return (
<div>
{isLoggedin ? (<AddNewCountryForm />) : (<p>You have to log in</p>)}
</div>
)
}
有人可以解释我应该如何继续解决这个问题吗?显然,如果用户已登录,我想呈现组件。
谢谢,
您需要将 isLoggedIn
转换为 React 状态而不是局部变量。
按照下面的代码,当 isLoggedIn
是 false
时,您应该看到 <p>You have to log in</p>
否则 AddNewCountryForm
组件应该呈现。
const renderForm = () => {
const [isLoggedin, setIsLoggedIn] = React.useState(false);
firebase.auth().onAuthStateChanged(function(user) {
setIsLoggedIn(!!user);
});
return (
<div>
{isLoggedin ? (<AddNewCountryForm />) : (<p>You have to log in</p>)}
</div>
)
}
希望对您有所帮助。