javascript - React 函数组件中不检查 Null 条件

标签 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 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/

相关文章:

javascript - 更新全局变量

javascript - 作为开发人员如何禁用鼠标手势?

javascript - html5 Canvas 移动元素

javascript - 突出显示带有注释的选择,在悬停时显示并且可编辑

javascript - 正则表达式 - 需要帮助获取字符串的特定部分

jquery - reactjs - 在 react 树之外公开 react 组件方法

javascript - React Material UI GridList 单元格不能正确换行

angular - 从另一个模块扩展 typescript 接口(interface)

typescript @types/chai - 你如何使用 Chai.Assertion?

javascript - 为什么 vue-property-decorator @Emit 在 Vue TypeScript 文件中不起作用?