我想在每次获取函数中遇到错误时都希望获得敬酒通知。我在返回之前使用组件内部的一个循环使用AccuWeather API来获取有关不同城市的数据。这是我的句柄错误功能:
export const handleErrors = (response) => {
if (!response.ok) {
return Promise.reject(response.statusText);
}
return response;}
这是我获取数据的组件:
import { useToasts } from 'react-toast-notifications';
import handleErrors from '../../handleErrors.js';
const mapStateToProps = state => ({
favorites:state.favorites.favorites})
export const Favorites = (props) => {
const { addToast } = useToasts();
let data = null;
props.favorites.map((city,i) => {
fetch(`http://dataservice.accuweather.com/currentconditions/v1/${city.CityKey}?apikey=${apiKey}`)
.then(handleErrors)
.then(response => response.json())
.then(res => {data = [...data,res[0]];console.log(data)})
.catch(error => addToast(error.message, { appearance: 'error' }))
});
return(
<div>
{data === null ? null : data.map((city,i => {
return(<FavoriteTile
city={city}
key={i}/>
)
</div>
)
}
现在尝试加载组件页面时,我收到了无限的Toast错误,并且页面崩溃。
[如果您使用的是功能组件,则将获取函数包装在useEffect中。
现在发生的事情是,每当您从该api获取内容时,您的吐司面包都将进行更新,因此组件将被重新渲染并在无限循环中再次调用fetch。
useEffect(() => {
props.favorites.map((city,i) => {
fetch(`http://dataservice.accuweather.com/currentconditions/v1/${city.CityKey}?
apikey=${apiKey}`)
.then(handleErrors)
.then(response => response.json())
.then(res => {data = [...data,res[0]];console.log(data)})
.catch(error => addToast(error.message, { appearance: 'error' }))
});
}, [])
您在哪里运行“获取代码”?我相信它应该在useEffect
(componentDidMount
)内部,否则当组件重新渲染时,它将一直在运行。