Javascript 三元运算符在react中工作不正常
因此,我有一个名为PrivateRoute.js的组件,它基本上可以保护一些路由,并在用户未登录时将其重定向到登录页面。我希望在Trigonal操作符中显示一条警报消息,我的警报通过,但几秒钟后我收到一个错误 私人路线Javascript 三元运算符在react中工作不正常,javascript,reactjs,if-statement,ternary-operator,Javascript,Reactjs,If Statement,Ternary Operator,因此,我有一个名为PrivateRoute.js的组件,它基本上可以保护一些路由,并在用户未登录时将其重定向到登录页面。我希望在Trigonal操作符中显示一条警报消息,我的警报通过,但几秒钟后我收到一个错误 私人路线 function PrivateRoute({ component: Component, ...rest }) { return ( <Route {...rest} render={props =>
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'
/>
)
}
/>
);
}
函数PrivateRoute({component:component,…rest}){
报税表(
/*如果“IsLoggedIn”位于本地存储(用户登录)中,则呈现PrivateRoute定义的组件*/
localStorage.getItem(“IsLoggedIn”)(
):alert('必须登录才能这样做!')(//否则,如果没有经过身份验证的用户,请将用户重定向到登录路由
)
}
/>
);
}
这是我在react中遇到的错误:
如何在三元运算符中显示警报而不出现此错误?JavaScript将
alert(…)(…)
视为希望将alert
的返回值作为函数调用,但alert
不返回函数。这就是错误告诉你的
如果要按顺序计算多个表达式,可以使用:
请注意,localStorage
仅存储字符串值,因此可能需要将localStorage.getItem(“IsLoggedIn”)
的返回值转换为实际的布尔值
说到这里,请注意,您应该避免使用
alert
,因为它是阻塞的。您有alert(“message”)()
。因此,它将调用警报
,然后尝试调用警报
返回的内容。但是调用alert
jus会给您提供未定义的
,无法调用。与React无关。不使用分号时发生。。。。您的代码基本上是var foo=alert('x');foo()。
condition ? case1 : (alert('some message'), <Redirect ... />)
// ^ ^ ^
render() {
const isLoggedIn = localStorage.getItem("IsLoggedIn");
if (!isLoggedIn) {
alert(...);
}
return <Route ... />;
}