我有一个react组件,它的开头是这样的:
function DetailedView({ country }) {
useEffect(() => {
axios
.get(
`https://api.openweathermap.org/data/2.5/weather?q=${country.capital[0]}&appid=${process.env.REACT_APP_WEATHER_API_KEY}`
)
.then((response) => setWeather(response.data));
}, [country]);
const [weather, setWeather] = useState({});
如您所见,有一个名为weather
的州,我需要基于country
属性进行查询,以接收首都城市,然后基于useEffect
挂钩内的城市设置weather
。
在我的代码后面,我最终引用了weather
变量。然而,最初它是未定义的,所以如果我试图在它上面使用点操作符从对象中检索属性,我会得到一个错误。为了解决这个问题,我最终不得不在从对象中访问属性之前检查对象是否为空:
{Object.keys(weather).length !== 0 ? (
<>
<p>Temperature: {weather.main.temp - 273}</p>
<img
src={`http://openweathermap.org/img/wn/${weather.weather[0].icon}@2x.png`}
alt="icon"
></img>
<p>Wind Speed: {weather.wind.speed} m/s</p>
</>
) : (
""
)}
这种方法是可行的,但似乎我在React中做了一些不符合习惯的事情。
谢谢你!
1条答案
按热度按时间46scxncf1#
你的方法是正确的。我经常看到这样的代码。
您可能希望返回
null
而不是空字符串:有些人喜欢使用较短的语句进行条件渲染: