首页 > 解决方案 > 这段代码狙击是做什么的还是只是一个错误

问题描述

我学习了 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();
}

标签: reactjsreact-props

解决方案


相当于这样说:

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 搜索中查找布尔短路。


推荐阅读