const AUTH_DISABLED = 0;
const AUTH_LOGIN = 1;
const AUTH_LOGOUT = 2;
function App() {
const [showLoginPopup, setShowLoginPopup] = useState(false);
const [authButtonState, setAuthButtonState] = useState(AUTH_DISABLED);
const handleClick = () => {
if ( authButtonState == AUTH_LOGOUT ) {
authGlobal.logout().then( () => { setAuthButtonState(AUTH_LOGIN) } );
} else {
setShowLoginPopup(true)
}
};
if (authButtonState === AUTH_DISABLED) {
authGlobal.tryAuthentication().then((loggedIn) => {
setAuthButtonState(loggedIn ? AUTH_LOGOUT : AUTH_LOGIN);
});
}
return (
<div className="main-container">
<div> Display </div>
<div className='main-controls'>
<button type='button' onClick={handleClick} disabled = {authButtonState == AUTH_DISABLED}>Log {authButtonState == AUTH_LOGOUT ? "Out" : "In"} </button>
<LoginPopup isVisible={showLoginPopup}/>
</div>
</div>
)
}
在上面的代码中,tryAuthentication
是异步的,有3条路径:凭据在本地存储中,凭据在URL中(刚刚用外部应用程序登录),或者没有登录用的东西.
我的问题是,在第二种情况下,按钮没有更改为"注销".状态永远不会更新,但then()
会正确调用setAuthButtonState()
.
把 twig 放进useEffect()
里有帮助,但我不知道为什么.
难道then()
不应该排队另一个重新呈现与新的状态没有UseEffect()
?