首页 > 解决方案 > 这个条件怎么是假的?

问题描述

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

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

变量的值如下:

我看到它的方式应该是正确的,因为这两个字符串彼此不相等并返回true,当错误为true时它也应该返回。所以我们有 true && true => true。

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

背景

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

标签: typescriptif-statementconditional-statements

解决方案


有时老派就是这样……你的输出是什么?

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

推荐阅读