在我的组件中,我想首先检查是否存在经过身份验证的用户:
const ReviewRoundOverall = (props) => {
if (authenticationService.currentUserValue === null)
history.push('/login');
const currentUserId = authenticationService.currentUserValue["id"];
//rest of the code
}
如果我有两个选项卡,并且我在其中一个选项卡中唱出来,然后刷新第二个选项卡中的页面,则会收到以下错误
TypeError: authentication_service_1.default.currentUserValue is null
对于行const currentUserId =authenticationService.currentUserValue[“id”];
如果我再次刷新页面,用户将导航到 /login
页面,不会出现错误。我想知道为什么在第一次刷新时 if (authenticationService.currentUserValue === null)
不起作用。
此外,我还有一个 NavMenu
,其中嵌套了所有组件,其中包含以下代码:
const NavMenu2 = (props) => {
if (authenticationService.currentUserValue == null || authenticationService.currentUserValue["id"] == null) {
authenticationService.logout();
history.push('/login');
}
useEffect(() => {
if (authenticationService.currentUserValue == null || authenticationService.currentUserValue["id"] == null) {
authenticationService.logout();
history.push('/login');
}
authenticationService.currentUser.subscribe(x => set_CurrentUser(x));
}, []);
}
这又不能解决问题。
有什么建议吗?
最佳答案
我猜它会在那里抛出错误,因为 history.push('/login');
行异步发生,这意味着其余代码将运行在重定向到登录页面之前。
所以我的建议是执行以下操作:
const ReviewRoundOverall = (props) => {
if (authenticationService.currentUserValue === null) {
history.push('/login');
} else {
const currentUserId = authenticationService.currentUserValue["id"];
//rest of the code
}
}
通过执行此操作,一旦 currentUserValue
的值为 null
,您就不会收到错误消息。
希望这会有所帮助!
关于javascript - React 函数组件中不检查 Null 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58747728/