【问题标题】:Ternary operator not working properly in react三元运算符在反应中无法正常工作
【发布时间】:2019-08-09 03:10:41
【问题描述】:

所以我有一个名为 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' 
            /> 
          ) 
        }
      />
    );
  }

这是我在 react 中遇到的错误:

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

【问题讨论】:

  • 你有alert("message")(&lt;component /&gt;)。所以它将调用alert,然后尝试调用alert 返回的内容。但是调用alert jus 给你undefined,这是不能调用的。与 React 无关。
  • 不使用分号时发生....你的代码基本上是var foo = alert('x'); foo(&lt;render&gt;)

标签: javascript reactjs if-statement ternary-operator


【解决方案1】:

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

如果要按顺序计算多个表达式,可以使用comma operator

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

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

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

  return <Route ... />;
}

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


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

【讨论】:

  • 可以,但最好将该逻辑从 JSX 中移出并放入 render 的函数体中。
  • @T.J.Crowder:对。
猜你喜欢
  • 2021-09-02
  • 2021-02-06
  • 2020-02-27
  • 1970-01-01
  • 2020-09-16
  • 2015-11-27
  • 2015-04-25
  • 1970-01-01
  • 2015-10-07
相关资源
最近更新 更多