简体   繁体   English

ReactJS提取导致无限循环

[英]ReactJS fetch causes infinite loop

I have two apps one of them is NodeJS listening 5000's port and the other is ReactJS listening 3000's port. 我有两个应用程序,其中一个是NodeJS监听5000的端口,另一个是ReactJS监听3000的端口。

I can return JSON from NodeJS like this ( http://localhost:5000/api/28/10/2018 ): 我可以像这样从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"]
}

I want to display this data with ReactJS but when I try fetch method it creates endless loop. 我想用ReactJS显示此数据,但是当我尝试获取方法时,它会创建无限循环。 How to solve this? 如何解决呢?

My ReactJS code: 我的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);
  }
}

This log many JSON object. 此日志中有许多JSON对象。

You call drawTable in the render method, which causes a fetch request. 您在render方法中调用drawTable ,这将导致获取请求。 When this completes, you put the response in state with setState which causes your component to re-render, and it continues like this indefinitely. 完成此操作后,您将响应设置为setState状态,这将导致您的组件重新呈现,并且它会无限期地继续运行。

You could instead get the data in componentDidMount and componentDidUpdate and just use the data in the render method. 您可以改为在componentDidMountcomponentDidUpdate获取数据,而仅在render方法中使用数据。

Example

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() {
    // ...
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM