未在反应功能组件中检查空条件

时间:2019-11-07 11:23:03

标签: javascript reactjs typescript

在我的组件中,我想首先检查是否有经过身份验证的用户:

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为空

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));
    }, []);

}

这又不能解决问题。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

我猜它在那里引发了错误,因为history.push('/login');行正在异步发生,这意味着其余代码将在重定向到登录页面之前运行。

所以我的建议是执行以下操作:

const ReviewRoundOverall = (props) => {
   if (authenticationService.currentUserValue === null) {
      history.push('/login');
   } else {
      const currentUserId = authenticationService.currentUserValue["id"];

      //rest of the code
   }
}

这样做,一旦获得null的{​​{1}}值,就不会收到错误消息。

我希望这会有所帮助!