reactjs - 使用 openweather API 和 ReactJS 处理错误 404
问题描述
我正在创建一个非常简单的应用程序,它显示世界城市的温度。
api 返回时出现错误 404 not found
。
我想处理错误 404 并显示一条类似You have to introduce a valid city name
.
我尝试将以下内容放在search
函数内部(最后)但无法正常工作:
if (weather.cod){
console.log("Erroooor");
}
这是我的完整代码:
import React, { useState } from 'react';
const api = {
key: "0e128f999e1fb1174d7af1d207406c01",
base: "https://api.openweathermap.org/data/2.5/"
}
function App() {
const [query, setQuery] = useState('');
const [weather, setWeather] = useState({});
const search = evt => {
if (evt.key === 'Enter') {
fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
.then(res => res.json())
.then(result => {
setWeather(result);
setQuery('');
});
}
}
const dateBuilder = (d) => {
let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
let day = days[d.getDay()];
let date = d.getDate();
let month = months[d.getMonth()];
let year = [d.getFullYear()];
return `${day} ${date} ${month} ${year}`;
}
return (
<div className={(typeof weather.main != "undefined")
? ((weather.main.temp > 20)
? 'app warm' : 'app cold') : 'app'}>
<main>
<div className="search-box">
<input
type="text"
className="search-bar search-focus"
placeholder="Type a city ..."
onChange={e => setQuery(e.target.value)}
value={query}
onKeyPress={search}
/>
</div>
{(typeof weather.main != "undefined") ? (
<div>
<div className="location-box">
<div className="location">{weather.name}, {weather.sys.country}</div>
<div className="date">{dateBuilder(new Date())}</div>
</div>
<div className="weather-box">
<div className="temp">
{Math.round(weather.main.temp)}ºC
</div>
<div className="weather">
{weather.weather[0].description}
</div>
</div>
</div>
) : ('')}
</main>
</div>
);
}
export default App;
解决方案
您可以添加 useState 来处理错误
添加
const [notFoundError,setNotFoundError]= useState(false)
作为回报,您可以添加 if 检查以检查错误是否为真
const App = ()=>{
const [notFoundError,setNotFoundError]= useState(false)
const [weather, setWeather] = useState({});
const search = evt => {
if (evt.key === 'Enter') {
fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
.then(res => res.json())
.then(result => {
// check if the API return the status
if(resuit.code == 404){
setNotFoundError(true)
}else{
// other status like 200
setWeather(result);
setQuery('');
}
});
}
}
return(
notFoundError ? <h1>You have to introduce a valid city name</h1> :(
<div> in case there is no error you can output the weather information </div>)
);
}
警告:请删除并更改您的 API 密钥,因为它是私有的,任何人都可以使用此密钥,您不应该在互联网上共享它
推荐阅读
- python - 训练模型——我们试图为整个数据集构建预测的类别有多少数据?
- python - 查找由点引用的多边形的最快方法(使用 Python、Fiona 和 Shapely)
- unit-testing - 由于无效的演员阵容,使用 googlemock 模拟副作用失败
- python - python 2x 到 python 3x 代码错误(绕过脚本)
- docker - 为什么 docker build 即使在我设置了时区后仍然询问我时区?
- html - 新页面未呈现 | 不能获取/
- macos - 在 macOS 上断开 Wifi 机场后重新连接?
- python - 如何将 NaN 转换为我的原始数据?
- ios - 如何在 SwiftUI 中制作无限的自定义轮子
- python - Python:检查时间是否在 1600-0900 之间