【发布时间】:2021-04-01 19:39:45
【问题描述】:
在用户身份验证页面中,我尝试使用从 API 调用中获取的响应令牌设置本地存储,然后导航到主页,我尝试在该主页显示配置文件详细信息,如果localstorage是有值的,虽然更新了本地存储,但是刷新首页后才能使用,所以想在进入首页前立即更新本地存储,这样就不需要了刷新,我没有使用 redux,所以任何人都可以在不使用 redux 的情况下帮助我。
提前致谢。
登录功能
login(event) {
fetch('api link', {
method: 'post',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
}),
})
.then((Response) => Response.json())
.then((result) => {
console.log('result is: ', result);
if (result.message === null) {
this.setState({ response: 'Invalid Username' });
} else if (result.message === 'INVALID_CREDENTIALS') {
this.setState({ response: 'Invalid Password' });
} else if (result.message === 'USER_DISABLED') {
this.setState({ response: 'Not verified' });
} else {
localStorage.setItem('ResetToken', result.token);
}
});
}
首页
{localStorage.getItem('ResetToken') ? (
<IconButton
aria-controls="simple-menu"
aria-haspopup="true"
color="inherit"
onClick={handleClick}
>
<AccountCircleIcon />
</IconButton>
) : null}
【问题讨论】:
-
您需要使用 props 传递状态变量和 setState 函数。您的身份验证组件应更新应用范围内的
isLoggedIn状态,并且您的主页应检查useEffect块内的isLoggedIn并相应地呈现。
标签: javascript reactjs