Javascript ReactJS fetch导致无限循环
我有两个应用程序,一个是NodeJS监听5000的端口,另一个是ReactJS监听3000的端口 我可以像这样从NodeJS()返回JSON: 我想用ReactJS显示这些数据,但当我尝试fetch方法时,它会创建无休止的循环。如何解决这个问题 我的代码:Javascript ReactJS fetch导致无限循环,javascript,reactjs,Javascript,Reactjs,我有两个应用程序,一个是NodeJS监听5000的端口,另一个是ReactJS监听3000的端口 我可以像这样从NodeJS()返回JSON: 我想用ReactJS显示这些数据,但当我尝试fetch方法时,它会创建无休止的循环。如何解决这个问题 我的代码: drawTable = (props) => { /* Some if-elseif that is not related to the question */ else { // here props.type ge
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对象 在render方法中调用
drawTable
,这会导致一个获取请求。完成后,您将响应置于setState
状态,这会导致组件重新渲染,并且它会无限期地继续这样
您可以改为在componentDidMount
和componentdiddupdate
中获取数据,并只在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() {
// ...
}
}
你在哪里调用
drawTable()
函数?@Jayce444我在render中调用函数,返回如下方法:{this.drawTable(this.props)}你在render方法中调用drawTable
,这会导致获取请求。完成后,您将响应置于setState
状态,这会导致组件重新渲染,并且它会无限期地继续这样。您可以在componentDidMount
和componentdiddupdate
@Tholle中获取数据,非常感谢您的回答!我完全理解它,但我仍然无法在代码中实现它。我如何在代码中实现它?阅读
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() {
// ...
}
}