reactjs - 这段代码狙击是做什么的还是只是一个错误
问题描述
我学习了 Reactjs 并阅读了很多代码,但无法理解这一点。
这是代码中的错误还是有什么作用?
我的意思是这一行:
this.props.onEnd && this.props.onEnd();
我知道这onEnd()
是对父母的回调,但它是如何工作的?代码;
/**
* Let parent components know that we reached the end of display
*/
_onEnd(isVisible) {
if (!isVisible) return;
this.props.onEnd && this.props.onEnd();
}
解决方案
相当于这样说:
if (this.props.onEnd != null) { // validate not null or undefined
this.props.onEnd(); // execute function
}
当表达如下:
this.props.onEnd && this.props.onEnd();
onEnd
如果为空或未定义,则表达式将短路。如果是,则表达式在逻辑上计算为:
false && this.props.onEnd()
在这种情况下,因为false && <anything else>
将始终评估为false
。如果and运算符的左侧评估为 false ,则运行时将不会评估右侧的调用。
同样,如果onEnd
是有效的,那么它在逻辑上被评估为:
true && this.props.onEnd()
在这种情况下,this.props.onEnd()
评估并执行。
有关更多信息,请在Internet 搜索中查找布尔短路。
推荐阅读
- scala - scala模式匹配字符串序列中的值
- sql-server - 如果条目是通过在多个表中输入数据的存储过程进行的,如何从表中恢复数据
- python - 机器学习二分类
- python - Tensorflow:动态地将值附加到张量
- spring-boot - 是否可以在 Spring Boot / JPA / Hibernate 中使用 Snowflake
- javascript - java - 如何在java脚本中定位privious元素的前一个元素?
- node.js - 在 Nodejs、Telegram API 中,messages.sendMultiMedia 方法不起作用?
- javascript - 如何在 ngFor 内单击以突出显示选定的单选按钮
- python - 使用 Python 请求下载文件时连接重置
- reactjs - 将图像置于文本之上