【发布时间】: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")(<component />)。所以它将调用alert,然后尝试调用alert返回的内容。但是调用alertjus 给你undefined,这是不能调用的。与 React 无关。 -
不使用分号时发生....你的代码基本上是
var foo = alert('x'); foo(<render>)
标签: javascript reactjs if-statement ternary-operator