Typescript 这个条件怎么是假的?
我正在用React用Typescript构建一个web应用程序,我的Typescript 这个条件怎么是假的?,typescript,if-statement,conditional-statements,Typescript,If Statement,Conditional Statements,我正在用React用Typescript构建一个web应用程序,我的componentDidMount()中有一个if语句,以便更改组件的状态并在特定条件下重新启动它。但我不知怎么搞不懂为什么这个表达式总是返回false。有人有什么想法或解释吗 componentDidMount() { if (this.props.altSrc != this.state.currentSrc && this.state.errored == true) { this.setState({
componentDidMount()
中有一个if语句,以便更改组件的状态并在特定条件下重新启动它。但我不知怎么搞不懂为什么这个表达式总是返回false。有人有什么想法或解释吗
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”
- 错误=正确
这段代码应该做的是将一个图像呈现到屏幕上,但是当找不到该图像时,它应该用一个替代图像(altSrc)替换该图像(currentSrc)。当找不到alt.图像时,render方法返回null。一切正常,当图像未加载时,我设法得到通知,然后将errored设置为true,只有if的条件出现问题 有时候,旧的skool是。。。你的产出是多少
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方法这是旧skool的强大功能:)