【发布时间】: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