首页 > 解决方案 > 三元运算符在反应中无法正常工作

问题描述

所以我有一个名为 PrivateRoute.js 的组件,它基本上保护一些路由并在用户未登录时将用户重定向到登录页面,我想在三元运算符内显示一条警报消息,我的警报通过但经过几次秒我得到一个错误

私人路由

function PrivateRoute({ component: Component, ...rest }) {
    return ( 
      <Route
        {...rest}
        render={props =>
        /*If "IsLoggedIn" is located inside the local storage(user logged in), then render the component defined by PrivateRoute */
            localStorage.getItem("IsLoggedIn")  ? (
            <Component {...props} />
          ) : alert('You must be logged in to do that!') (  //else if there's no authenticated user, redirect the user to the signin route 
            <Redirect 
              to='/signin' 
            /> 
          ) 
        }
      />
    );
  }

这是我在反应时遇到的错误:

反应错误

如何在三元运算符中显示警报而不出现此错误?

标签: javascriptreactjsif-statementternary-operator

解决方案


JavaScript 认为alert(...) (...)您想将 的返回值alert作为函数调用,但alert不返回函数。这就是错误告诉你的。

如果要按顺序计算多个表达式,可以使用逗号运算符

condition ? case1 : (alert('some message'), <Redirect ... />)
//                  ^                     ^                 ^

您可以通过在语句之前移动alert调用来实现相同的目的,这也使您的代码更简单:return

render() {
  const isLoggedIn = localStorage.getItem("IsLoggedIn");
  if (!isLoggedIn) {
    alert(...);
  }

  return <Route ... />;
}

请注意,localStorage仅存储字符串值,因此您可能需要将返回值转换为localStorage.getItem("IsLoggedIn")实际的布尔值。


说了这么多,注意你应该避免使用,alert因为它是阻塞的。


推荐阅读