javascript - 三元运算符在反应中无法正常工作
问题描述
所以我有一个名为 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'
/>
)
}
/>
);
}
这是我在反应时遇到的错误:
如何在三元运算符中显示警报而不出现此错误?
解决方案
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
因为它是阻塞的。
推荐阅读
- python - 理解类问题的函数的目的
- c++ - 如何操作重载“>>”?
- swift - 如何将方法传递给采用闭包的变量?
- java - 初学者在开始使用 MySQL 时是否有任何理由使用 InnoDB
- ios - 找出在长按和点击之间不同时按下了哪个按钮。迅速
- java - 在时间窗口内每 30 分钟运行一次任务
- ios - 如何选择将 Core Data 存储的本地数据备份到 iCloud
- swift - 快速属性初始化程序在“自我”可用之前运行
- reactjs - 使用 shortid 和 react-final-form 时超出最大更新深度
- java - 将整数列表添加到 csv 文件 (JAVA)