未捕获错误:重新渲染过多.React限制渲染次数,以防止出现无限循环.React Hooks,承诺



我正在尝试将一些axios调用结果呈现到映射到当前组件的餐厅信息列表中。所以axios调用结果是我当前位置到我使用谷歌距离矩阵API的餐厅位置之间的距离。因此,其中一个参数(我的当前位置(将是恒定的,我想生成我当前位置与我将在该组件中列出的每个餐厅之间的距离。因此,我将道具映射到当前组件上,如下所示:

`return (
<div>
<ul>
{props.restaurants.map((item, index) => {
return (
<div>
<h3>{item.name}</h3>
<p>
{item.description}
<br />
{item.address}
<br />
{item.phone}
<br />
{distance}
</p>
</div>
);
})}
</ul>
</div>
);`

对于距离,我需要使用props.restaurants中的餐厅位置对我的快递服务器进行axios调用,并调用谷歌api。。。axios调用以及调用googleapi和express服务器的函数工作正常(使用poster测试(我正在尝试使用React Hooks,如下所示:

`import React, { useState, useEffect } from 'react';
import axios from 'axios';
const RestaurantsList = (props) => {
const [restPlaceId, setCurPlaceID] = useState();
const [distance, setDistance] = useState([]);
useEffect(() => {
axios
.get(`/distance/?org=${props.currentPlaceId}&des=${curPlaceId}`)
.then((result) => {
setDistance(result);
});
}, [restPlaceId]);
if (props.restaurants.length === 0) {
return <span>please wait for related product to load</span>;
} else {
return (
<div>
<ul>
{props.restaurants.map((item, index) => {
setCurPlaceID(item.place_id);
return (
<div>
<h3>{item.name}</h3>
<p>
{item.description}
<br />
{item.address}
<br />
{item.phone}
<br />
{distance}
</p>
</div>
);

})}
</ul>
</div>
);
}
};
export default RestaurantsList;`

所以我尝试在.map循环中每次更新restPlaceId,然后使用usEffect获得新的距离。但是,我收到以下错误消息:Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.有人能帮我处理那个错误信息吗或者有没有更好的办法来拉近与每家餐厅的距离?

这里的错误是在状态呈现时更新状态,
setCurPlaceID(item.place_id);

你应该在你的效果中称之为:D

您在渲染内部调用setCurPlaceID(item.place_id),然后执行useEffect,它的dependencies中有restPlaceId

每次props.restaurants.map()循环时,都会执行setCurPlaceID(item.place_id),然后执行您的useEffect,循环会一直持续下去

在useEffect中调用setCurPlaceID(item.place_id);,而不是在渲染中调用

最新更新