ReactJS fetch 导致无限循环
Posted
技术标签:
【中文标题】ReactJS fetch 导致无限循环【英文标题】:ReactJS fetch causes infinite loop 【发布时间】:2019-04-07 17:29:06 【问题描述】:我有两个应用,一个是 NodeJS 监听 5000 的端口,另一个是 ReactJS 监听 3000 的端口。
我可以像这样从 NodeJS 返回 JSON (http://localhost:5000/api/28/10/2018):
"date": "28.10.2018",
"across": [
"no": "1", "text": "Warning about an incoming projectile",
"no": "5", "text": "Rapper/producer behind Beats headphones",
"no": "6", "text": "Noble gas below xenon on the periodic table",
"no": "7", "text": "Setting for much of \"Finding Nemo\"",
"no": "8", "text": "Looney Tunes character who says \"Th-th-th-that's all, folks!\""
],
"down": [
"no": "1", "text": "Harry's enemy at Hogwarts",
"no": "2", "text": "Milk dispenser",
"no": "3", "text": "Sound from a frog",
"no": "4", "text": "Country music star Chesney",
"no": "5", "text": "The shape of water?"
],
"cells": ["-1","1","2","3","4","5","0","0","0","0","6","0","0","0","0","7","0","0","0","0","8","0","0","0","0"]
我想用 ReactJS 显示这些数据,但是当我尝试 fetch 方法时,它会创建无限循环。如何解决?
我的 ReactJS 代码:
drawTable = (props) =>
/* Some if-elseif that is not related to the question */
else
// here props.type get an array that hold input from terminal
let day, month, year;
day = props.type[1];
month = props.type[2];
year = props.type[3];
if (day === undefined || month === undefined || year === undefined)
console.log("Please use get-old command properly!");
console.log("Usage:\nget-old day month year");
console.log("Example:\nget-old 28 10 2018");
return idle;
// If arguments defined go fetch
let url = `http://localhost:$REACT_PORT/old/$day/$month/$year`;
fetch(url)
.then((response) => response.json())
.then((data) =>
this.setState(data: data);
)
.catch((error) =>
console.error(error);
);
console.log(this.state.data);
这记录了许多 JSON 对象。
【问题讨论】:
你在哪里调用drawTable()
函数?
@Jayce444 我在渲染中调用函数,返回方法如下:this.drawTable(this.props)
您在 render 方法中调用 drawTable
,这会导致一个 fetch 请求。完成后,您将响应置于setState
状态,这会导致您的组件重新渲染,并且它会无限期地继续下去。您可以改为获取 componentDidMount
和 componentDidUpdate
中的数据。
@Tholle 非常感谢您的回答!我完全明白了,但我仍然无法在我的代码中实现它。如何在代码中实现它?
阅读reactjs.org/docs/react-component.html#render
【参考方案1】:
您在渲染方法中调用drawTable
,这会导致获取请求。完成后,您将响应置于setState
状态,这会导致您的组件重新渲染,并且它会无限期地继续下去。
您可以改为获取 componentDidMount
和 componentDidUpdate
中的数据,然后在 render 方法中使用数据。
示例
class MyComponent extends React.Component
// ...
componentDidMount()
this.fetchData();
componentDidUpdate(prevProps)
const [, prevDay, prevMonth, prevYear] = prevProps.type;
const [, day, month, year] = this.props.type;
if (prevDay !== day || prevMonth !== month || prevYear !== year)
this.fetchData();
fetchData = () =>
const [, day, month, year] = this.props.type;
const url = `http://localhost:$REACT_PORT/old/$day/$month/$year`;
fetch(url)
.then(response => response.json())
.then(data =>
this.setState( data );
)
.catch(error =>
console.error(error);
);
;
render()
// ...
【讨论】:
以上是关于ReactJS fetch 导致无限循环的主要内容,如果未能解决你的问题,请参考以下文章
放大 dynamodb graphql fetch 函数在循环中无限运行