[英]Why do my fetch request causes an infinite error loop in ReactJs using React Toast Notifications
每次我在 fetch 函數中發現錯誤時,我都想得到一個 toast 通知。我在返回之前在組件內使用一個循環,以使用 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>
)
}
現在,當嘗試加載組件頁面時,我收到了無限的吐司錯誤並且頁面崩潰了。
你在哪里運行你的“獲取代碼”? 我相信它應該在useEffect
( componentDidMount
) 內的某個地方,否則它會在組件重新渲染時一直運行。
如果您正在使用功能組件,只需使用 useEffect 包裝您的 fetch 函數。
現在發生的事情是每次你從那個 api 中獲取一些東西時,你的 toast 正在更新,因此組件正在被重新渲染並在無限循環中再次調用 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' }))
});
}, [])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.