我检查道具的方式有什么不同吗?
Are there any differences in how I am checking props?
我一直在研究以不同且更易读的方式编写代码,并且最近在我的 React-Redux 应用程序中编写我的 if 语句略有不同。以这种方式编写我的函数有什么功能上的差异吗?在此示例中,在 Login
容器中,componentWillReceiveProps
检查是否在 Redux 存储中定义了用户身份(通过 mapStateToProps 访问。)如果 nextProps.isLoggedIn
是 true
,然后用户将被推送到我的应用程序中的根路由。
据我所知,下面编写的两个代码片段以相同的方式运行,但我很想知道是否存在它们不以同义方式运行的边缘情况。
componentWillReceiveProps(nextProps) {
if (nextProps.isLoggedIn) {
browserHistory.push('/');
}
}
对比
componentWillReceiveProps(nextProps) {
!!(nextProps.isLoggedIn) && browserHistory.push('/');
}
connect
我容器的一部分:
export default connect(
state => ({
isLoggedIn: state.auth.identity,
}),
{ login },
)(Login);
在我的减速器中,identity
的默认参数是 null
。当用户成功登录时,identity
值将更新为一个对象,该对象作为身份验证后端的响应返回。
逻辑运算符 &&
和 ||
使用 short-circuiting evaluation,这意味着如果第一个表达式的计算结果为某个值,它们将不会计算第二个表达式。
通常可以使用它们来消除 if
语句并使您的代码更具功能性,减少强制性。
在您的特定情况下,null
是一个虚假值,因此:
if (nextProps.isLoggedIn) {
browserHistory.push('/');
}
具有与以下完全相同的输出:
nextProps.isLoggedIn && browserHistory.push('/');
if
statements 如果提供的表达式为真,则执行语句,因此它们使用相同的规则进行评估。使用 if
的主要区别在于您可以计算语句而不是仅计算表达式。例如,您不能在 &&
或 ||
.
的第二部分声明 var
我一直在研究以不同且更易读的方式编写代码,并且最近在我的 React-Redux 应用程序中编写我的 if 语句略有不同。以这种方式编写我的函数有什么功能上的差异吗?在此示例中,在 Login
容器中,componentWillReceiveProps
检查是否在 Redux 存储中定义了用户身份(通过 mapStateToProps 访问。)如果 nextProps.isLoggedIn
是 true
,然后用户将被推送到我的应用程序中的根路由。
据我所知,下面编写的两个代码片段以相同的方式运行,但我很想知道是否存在它们不以同义方式运行的边缘情况。
componentWillReceiveProps(nextProps) {
if (nextProps.isLoggedIn) {
browserHistory.push('/');
}
}
对比
componentWillReceiveProps(nextProps) {
!!(nextProps.isLoggedIn) && browserHistory.push('/');
}
connect
我容器的一部分:
export default connect(
state => ({
isLoggedIn: state.auth.identity,
}),
{ login },
)(Login);
在我的减速器中,identity
的默认参数是 null
。当用户成功登录时,identity
值将更新为一个对象,该对象作为身份验证后端的响应返回。
逻辑运算符 &&
和 ||
使用 short-circuiting evaluation,这意味着如果第一个表达式的计算结果为某个值,它们将不会计算第二个表达式。
通常可以使用它们来消除 if
语句并使您的代码更具功能性,减少强制性。
在您的特定情况下,null
是一个虚假值,因此:
if (nextProps.isLoggedIn) {
browserHistory.push('/');
}
具有与以下完全相同的输出:
nextProps.isLoggedIn && browserHistory.push('/');
if
statements 如果提供的表达式为真,则执行语句,因此它们使用相同的规则进行评估。使用 if
的主要区别在于您可以计算语句而不是仅计算表达式。例如,您不能在 &&
或 ||
.
var