gpt4 book ai didi

javascript - 在 React 和 JSX 中反转 if 语句

转载 作者:行者123 更新时间:2023-11-30 07:51:28 27 4
gpt4 key购买 nike

我正在使用一个功能组件,使用基本的 if 语句在 React 中打印出一些数据

import React from 'react'

export default function Weather (props) {
let obj = props.data
if(obj === undefined || {}) {
console.log(obj) <---returns desired object
return <div>Enter in a city, zipcode, or address</div>
} else {
console.log(obj) <-- returns undefined
return<div>
<p>{obj.minutely.summary}</p>
<p>{obj.currently.temperature}</p>
<p>{obj.currently.humidity}</p>
<p>{obj.currently.windSpeed}</p>
<p>{obj.currently.uvIndex}</p>
<p>{obj.currently.precipProbability}</p>
</div>

}
}

if 语句的逻辑是这样的:如果数据是undefined 打印出输入地址的指令,否则打印出数据。

令人困惑的是,if 语句似乎忽略了条件语句,因为

if(obj === undefined || {}) {
console.log(obj)
return <div>Enter in a city, zipcode, or address</div>
}

这个 console.log 返回我所有的数据,即使它只应该在对象未定义时运行。

第二个 if 语句甚至没有打印出来。我试过将两者调换,看起来像这样:

if(obj !== undefined || {}) {
return<div>
<p>{obj.minutely.summary}</p>
<p>{obj.currently.temperature}</p>
<p>{obj.currently.humidity}</p>
<p>{obj.currently.windSpeed}</p>
<p>{obj.currently.uvIndex}</p>
<p>{obj.currently.precipProbability}</p>
</div>
} else {
return <div>Enter in a city, zipcode, or address</div>

}

但是,因为它正在尝试寻找一个尚未设置的对象,所以它仍然会在第一个 if 语句上停止并作为未定义的铃声响起(尽管这是预期的)

有什么建议吗?

最佳答案

if(obj === undefined || {}) {
...
} else { ...

始终为真,因为 {} 是一个真值。

我想你的意思是:

if(obj === undefined || obj === {}) {
...
} else { ...

但还是...

> {} === {}
false

为了检查该对象是否为空:

if(obj === undefined || Object.getOwnPropertyNames(obj).length === 0){
...
} else { ...

关于javascript - 在 React 和 JSX 中反转 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52298597/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com