为什么我的提取请求使用React Toast通知在ReactJs中导致无限错误循环

问题描述 投票:0回答:2

我想在每次获取函数中遇到错误时都希望获得敬酒通知。我在返回之前使用组件内部的一个循环使用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错误,并且页面崩溃。

javascript reactjs error-handling fetch toast
2个回答
1
投票

[如果您使用的是功能组件,则将获取函数包装在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' }))
  });
}, [])

1
投票

您在哪里运行“获取代码”?我相信它应该在useEffectcomponentDidMount)内部,否则当组件重新渲染时,它将一直在运行。

© www.soinside.com 2019 - 2024. All rights reserved.