typescript - 这个条件怎么是假的?
问题描述
我正在使用 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})
}
}
变量的值如下:
- altSrc = "www.xxx.com/not-found.jpg"
- currentSrc = "www.xxx.com/image.jpg"
- 错误=真
我看到它的方式应该是正确的,因为这两个字符串彼此不相等并返回true,当错误为true时它也应该返回。所以我们有 true && true => true。
所以我问我在 if 语句的条件下缺少什么?
背景
这段代码应该做的是将图像渲染到屏幕上,但是当找不到图像时,它应该用替代图像(altSrc)替换图像(currentSrc)。当 alt。未找到图像渲染方法返回 null。一切正常我设法在图像未加载时得到通知,然后将 errored 设置为 true,只有 if 的条件给了麻烦。
解决方案
有时老派就是这样……你的输出是什么?
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
推荐阅读
- gradle - dependsOn 另一个带有参数值的任务
- mysql - 无法在虚拟环境中为 django 安装 mysqlclient
- svg - 使用 svg 时,我是否需要调整 viewBox 大小的数字和启用背景中的相同数字?
- google-cloud-platform - 对外部 Google 品牌帐号的 Oauth 访问权限
- cmake - 运行 cmake std 教程第 2 步示例时出错
- python - 欧几里得单应性优化python
- bash - 如何在 ec2 上运行 scp
- postgresql - 如何在 RDS postgres 中设置查询超时时间
- php - 传递给 MongoDB\Driver\Server::executeBulkWrite() 的参数 3 必须是 MongoDB\Driver\WriteConcern 的实例或 null
- java - 在 Android 的弹出窗口上更新 textview 时出错