这是代码
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
div.example {
max-width: 460px;
height: 170px;
padding: 40px;
border: 1px solid black;
text-align: center;
font-size: 65px;
font-family: courier;
}
@media screen and (min-width: 601px) {
div.example {
font-size: 65px;
}
}
@media screen and (max-width: 600px) {
div.example {
font-size: 30px;
}
}
</style>
</head>
<body>
<div class="example">
<p>marketer</p>
</div>
<div class="example">
<p>creator</p>
</div>
<div class="example">
<p>innovator</p>
</div>
<div class="example">
<p>collaborator</p>
</div>
</div>
<script>
var slideIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("example");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
slideIndex++;
if (slideIndex > x.length) {slideIndex = 1}
x[slideIndex-1].style.display = "block";
setTimeout(carousel, 400);
}
</script>
</body>
</html>
我正在使用语义UI进行样式和Firebase身份验证。
问题是我无法将signIn用户的状态设置为用户状态。当我在import React, { useState } from 'react';
import firebase from 'firebase';
const GoogleAuth = () => {
const [user, setUser] = useState({});
const [isSignedIn, setIsSignedIn] = useState(null);
var provider = new firebase.auth.GoogleAuthProvider();
provider.addScope('https://www.googleapis.com/auth/userinfo.email');
firebase.auth().useDeviceLanguage();
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
setIsSignedIn(true);
} else {
setIsSignedIn(false)
}
});
const login = () => {
firebase.auth().signInWithPopup(provider).then(function(result) {
// signed-in user info.
setUser(result.user);
setIsSignedIn(true);
}).catch(function(error) {
console.log(error);
});
}
const logout = () => {
firebase.auth().signOut().then(function() {
console.log('logout success');
setIsSignedIn(false);
}).catch(function(error) {
console.log('logout error');
});
}
const renderButton = () => {
if(isSignedIn === null) {
return(
<div>
<div className="ui active inline loader"></div>
</div>
);
} else if (isSignedIn) {
return(
<div className="ui negative basic animated button" tabIndex="" onClick={logout}>
<div className="visible content">SignOut</div>
<div className="hidden content">
<i className="right google icon"></i>
</div>
</div>
);
} else {
return(
<div className="ui positive basic animated button" tabIndex="0" onClick={login}>
<div className="visible content">SignIn</div>
<div className="hidden content">
<i className="right google icon"></i>
</div>
</div>
);
}
}
return (
<div>
{renderButton()}
</div>
);
};
export default GoogleAuth;
函数中使用setUser(result.user)
时,用户状态仍然是一个空对象。但是登录成功,如果我使用控制台login()
登录,它会显示已登录的用户对象。
我在做什么错?为什么result.user
在这里不起作用?
答案 0 :(得分:1)
假设您的result.user是一个对象,现在将其设置为
setUser({...result.user});
在某些情况下,直接设置状态不更新对我有用。