我有两个应用程序,其中一个是NodeJS监听5000的端口,另一个是ReactJS监听3000的端口。
我可以像这样(http://localhost:5000/api/28/10/2018)从NodeJS返回JSON:
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Vue.delete">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model.lazy="num" />
<p>out: {{ num }}</p>
</div>
</body>
我想用ReactJS显示此数据,但是当我尝试获取方法时,它会创建无限循环。该如何解决?
我的ReactJS代码:
{
"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"]
}
此日志中有许多JSON对象。
答案 0 :(得分:1)
您在render方法中调用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() {
// ...
}
}