【问题标题】:How is this condition false?这个条件怎么是假的?
【发布时间】:2018-11-15 13:36:06
【问题描述】:

我正在使用 React 在 Typescript 中构建一个 Web 应用程序,我的 componentDidMount() 中有一个 if 语句,以便更改组件的状态并在某些条件下重新呈现它。但我不知何故无法理解为什么表达式总是返回错误。有人有想法或解释吗?

componentDidMount() {
if (this.props.altSrc != this.state.currentSrc && this.state.errored == true) {
  this.setState({...this.state, errored: false, currentSrc: this.props.altSrc})
  } 
}

变量的值如下:

  • altSrc = "www.xxx.com/not-found.jpg"
  • currentSrc = "www.xxx.com/image.jpg"
  • 错误 = 真

在我看来,结果应该是真的,因为两个字符串彼此不相等并返回真,当错误为真时它也应该返回。所以我们有 true && true => true。

所以我问我在 if 语句的条件下缺少什么?

背景

这段代码应该做的是将图像渲染到屏幕上,但是当找不到图像时,它应该用替代图像(altSrc)替换图像(currentSrc)。当 alt。未找到图像,渲染方法返回 null。一切正常我设法在图像未加载时得到通知,然后将 errored 设置为 true,只有 if 的条件给了麻烦。

【问题讨论】:

    标签: typescript if-statement conditional-statements


    【解决方案1】:

    有时老派是一种方式......你的输出是什么?

    console.log(this.props.altSrc, typeof this.props.altSrc, this.state.currentSrc, typeof this.state.currentSrc, (this.props.altSrc != this.state.currentSrc));
    console.log(this.state.errored, typeof this.state.errored, this.state.errored == true);
    
    if (this.props.altSrc != this.state.currentSrc && this.state.errored == true) {
        console.log('WE MADE IT INTO THE CONDITION');
        this.setState({...this.state, errored: false, currentSrc: this.props.altSrc})
    } 
    

    我的模拟显示要么值与您的预期不同,要么发生了一些类型杂耍。

    const altSrc = 'abcde' as string;
    const currentSrc = 'fghij' as string;
    const errored = true as boolean;
    
    console.log(altSrc, typeof altSrc, currentSrc, typeof currentSrc, (altSrc != currentSrc));
    console.log(errored, typeof errored, errored == true);
    
    if (altSrc != currentSrc && errored == true) {
        console.log('WE MADE IT INTO THE CONDITION');
    } 
    

    输出:

    abcde string fghij string true
    true boolean true
    WE MADE IT INTO THE CONDITION
    

    【讨论】:

    • 我得到了false "boolean" false 我想我知道当我更改变量errored 和setState 方法会查看组件的didmount 方法时它与问题有什么关系
    • 这就是老派的力量:)
    猜你喜欢
    • 2016-12-04
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 2019-12-30
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多